Skip to content

Commit

Permalink
增加批量导入
Browse files Browse the repository at this point in the history
  • Loading branch information
limingxinleo committed Jul 4, 2024
1 parent 5cfdb69 commit 5a4b652
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
28 changes: 28 additions & 0 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,34 @@ public function toBody(): array
];
}

public function bulk(
array $docs,
#[ArrayShape([
'refresh' => 'bool',
'retry_on_conflict' => 'int',
])]
?array $settings = null
): bool {
$settings ??= $this->document->getConfig()->getUpdateSettings();

$body = [];
foreach ($docs as $doc) {
$body[] = [
'index' => [
'_index' => $this->document->getIndex(),
'_id' => $doc[$this->document->getKey()],
],
];

$body[] = $doc;
}

return $this->document->getClient()->bulk([
'body' => $body,
...$settings,
])->asBool();
}

public function update(
array $doc,
mixed $id = null,
Expand Down
20 changes: 18 additions & 2 deletions tests/Cases/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ public function testUpdateAndGet()
public function testLTAndGT()
{
$res = Foo::query()->where('id', '>', 4)->get();
$this->assertSame(1, $res->count());
$this->assertSame(3, $res->count());

$res = Foo::query()->where('id', '>=', 4)->get();
$this->assertSame(2, $res->count());
$this->assertSame(4, $res->count());
}

public function testTerms()
Expand Down Expand Up @@ -166,4 +166,20 @@ public function testOrWhereClosure()
$this->assertSame(2, $res->first()['id']);
$this->assertSame(5, $res->last()['id']);
}

public function testBulk()
{
$res = Foo::query()->bulk([
['id' => 6, 'name' => 'elastic', 'summary' => $id = uniqid()],
['id' => 7, 'name' => 'elastic2', 'summary' => $id2 = uniqid()],
]);

$this->assertTrue($res);

$first = Foo::query()->where('id', 6)->get()->first();
$this->assertSame($id, $first['summary']);

$first = Foo::query()->where('id', 7)->get()->first();
$this->assertSame($id2, $first['summary']);
}
}
7 changes: 7 additions & 0 deletions tests/put_documents.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,10 @@ public function getMapping(): array
foreach ($docs as $doc) {
Foo::query()->update($doc, $doc['id']);
}

$res = Foo::query()->bulk([
['id' => 6, 'name' => 'elastic', 'summary' => uniqid()],
['id' => 7, 'name' => 'elastic2', 'summary' => uniqid()],
]);

var_dump($res);

0 comments on commit 5a4b652

Please sign in to comment.