Skip to content

Commit b1c1fc8

Browse files
committed
Move bulk index payload onto document
1 parent 4d9899a commit b1c1fc8

3 files changed

Lines changed: 41 additions & 8 deletions

File tree

src/Documents/Document.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,25 @@ public function get(string $key): mixed
4444
return $this->source[$key] ?? null;
4545
}
4646

47+
/**
48+
* Get the OpenSearch bulk index operation payload.
49+
*
50+
* @return array{0: array{index: array<string, string>}, 1: array<string, mixed>}
51+
*/
52+
public function toBulkIndex(?string $routing = null): array
53+
{
54+
$index = ['_id' => $this->id];
55+
56+
if (! is_null($routing)) {
57+
$index['routing'] = $routing;
58+
}
59+
60+
return [
61+
compact('index'),
62+
$this->source,
63+
];
64+
}
65+
4766
/**
4867
* Get the array representation of the document.
4968
*

src/Documents/DocumentManager.php

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,10 @@ public function index(
4141
];
4242

4343
foreach ($documents as $document) {
44-
$index = ['_id' => $document->id()];
45-
46-
if ($routing && $routing->has($document->id())) {
47-
$index['routing'] = $routing->get($document->id());
48-
}
49-
50-
$params['body'][] = compact('index');
51-
$params['body'][] = $document->source();
44+
array_push(
45+
$params['body'],
46+
...$document->toBulkIndex($routing?->get($document->id()))
47+
);
5248
}
5349

5450
$response = $this->client->bulk($params);

tests/Unit/Documents/DocumentTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,21 @@
2121
'source' => ['title' => 'test'],
2222
], $document->toArray());
2323
});
24+
25+
test('bulk index payload can be retrieved', function () {
26+
$document = new Document('1', ['title' => 'test']);
27+
28+
$this->assertSame([
29+
['index' => ['_id' => '1']],
30+
['title' => 'test'],
31+
], $document->toBulkIndex());
32+
});
33+
34+
test('bulk index payload can be retrieved with routing', function () {
35+
$document = new Document('1', ['title' => 'test']);
36+
37+
$this->assertSame([
38+
['index' => ['_id' => '1', 'routing' => 'tenant-1']],
39+
['title' => 'test'],
40+
], $document->toBulkIndex('tenant-1'));
41+
});

0 commit comments

Comments
 (0)