Skip to content

Commit 4237d91

Browse files
fix: implement actual document deletion in Elasticsearch
Previously, removeFromElasticsearch() only performed a search but never deleted the matching documents. This caused a memory leak in ES where deleted model records would leave orphaned tokens in the index. Changes: - Added deleteByQuery() method to ElasticsearchService - Updated removeFromElasticsearch() to use delete-by-query API - Removed obsolete comment about future optimization - Improved PHPDoc to reflect actual deletion behavior This fixes the critical issue where ES tokens accumulated indefinitely after model deletion.
1 parent 6975c73 commit 4237d91

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/Services/ElasticsearchService.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,19 @@ public function search(string $index, array $query): array
8888

8989
return $response->json('hits.hits', []);
9090
}
91+
92+
/**
93+
* Delete documents matching a query from an Elasticsearch index.
94+
*
95+
* @param string $index The Elasticsearch index name.
96+
* @param array<string, mixed> $query The Elasticsearch query body.
97+
* @return bool True if successful, false otherwise.
98+
*/
99+
public function deleteByQuery(string $index, array $query): bool
100+
{
101+
$url = "{$this->host}/{$index}/_delete_by_query";
102+
$response = Http::post($url, $query);
103+
104+
return $response->successful();
105+
}
91106
}

src/Traits/HasEncryptedSearchIndex.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,10 @@ protected function syncToElasticsearch(array $rows): void
172172
}
173173

174174
/**
175-
* Remove this models tokens from the configured Elasticsearch index.
175+
* Remove this model's tokens from the configured Elasticsearch index.
176176
*
177-
* Uses a boolean query to match documents by model_type and model_id.
177+
* Uses delete-by-query to efficiently remove all documents matching
178+
* the model_type and model_id.
178179
*
179180
* @return void
180181
*/
@@ -195,8 +196,7 @@ protected function removeFromElasticsearch(): void
195196
];
196197

197198
try {
198-
$service->search($index, $query);
199-
// Optional: replace with Elasticsearch delete-by-query API for optimization
199+
$service->deleteByQuery($index, $query);
200200
} catch (\Throwable $e) {
201201
logger()->warning("Failed to remove Elasticsearch docs for model {$this->getKey()}: {$e->getMessage()}");
202202
}

0 commit comments

Comments
 (0)