Skip to content

Commit

Permalink
perf: optimized adding and committing of documents
Browse files Browse the repository at this point in the history
  • Loading branch information
rasstislav committed Sep 13, 2023
1 parent 74ee746 commit 7e12851
Showing 1 changed file with 8 additions and 32 deletions.
40 changes: 8 additions & 32 deletions src/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -317,40 +317,22 @@ public function rebuild(): void
protected array $uncommitted = [];

/**
* @param Document|array $documents
* @param Document $document
* @param bool $commit
* @return $this
* @throws NotFoundExceptionInterface
* @throws Throwable
*/
public function add(Document|array $documents, bool $commit = true): self
public function add(Document $document, bool $commit = true): self
{
if (!is_array($documents)) {
$documents = [$documents];
}

$excludedClasses = static::config()->uninherited('excluded_classes') ?? [];

foreach ($documents as $key => $document) {
if (
!($document instanceof Document)
|| in_array($document->record::class, $excludedClasses)
) {
unset($documents[$key]);
}
}
if (!$excludedClasses || !in_array($document->record::class, $excludedClasses)) {
$this->uncommitted[] = $document->toArray();

if (empty($documents)) {
return $this;
}

$this->uncommitted = array_merge(
$this->uncommitted,
$documents
);

if ($commit) {
$this->commit();
if ($commit) {
$this->commit();
}
}

return $this;
Expand All @@ -367,13 +349,7 @@ protected function commit(): self
return $this;
}

$documents = [];

foreach ($this->uncommitted as $document) {
$documents[] = $document->toArray();
}

static::get_client()->index($this->getIndexName())->addDocuments($documents, 'ID');
static::get_client()->index($this->getIndexName())->addDocuments($this->uncommitted, 'ID');

$this->uncommitted = [];

Expand Down

0 comments on commit 7e12851

Please sign in to comment.