public function safeDeleteDoc(ElasticsearchService $es)
{
//删除前先判断是否存在(推荐)
$client = $es->getClient();
$exists = $client->exists([
'index' => 'novel',
'id' => '1'
]);
if (!$exists) {
return ['message' => '文档不存在'];
}
return $client->delete([
'index' => 'novel',
'id' => '1'
]);
}
#[RequestMapping(path:'deleteByQuery',methods:'get')]
public function deleteByQuery(ElasticsearchService $es)
{
//根据条件删除(_delete_by_query)
//删除 name 包含“测试”的文档
$client = $es->getClient();
return $client->deleteByQuery([
'index' => 'novel',
'conflicts' => 'proceed',//生产环境建议(非常重要)条件删除一定要加 conflicts=proceed
'body' => [
'query' => [
'match' => [
'name' => '测试'
]
]
]
]);
//删除 author = 某个作者
$client->deleteByQuery([
'index' => 'novel',
'body' => [
'query' => [
'term' => [
'author' => '猫腻'
]
]
]
]);
}
#[RequestMapping(path:'bulkDelete',methods:'get')]
public function bulkDelete(ElasticsearchService $es)
{
//批量删除(多条 ID)
//大量删除用 _delete_by_query,不要用循环
/*不要用foreach ($ids as $id) {
$client->delete([...]);
}
要用
$client->bulk([...]);
// 或
$client->deleteByQuery([...]);
*/
$client = $es->getClient();
$ids = ['10', '11', '12'];
$params = ['body' => []];
foreach ($ids as $id) {
$params['body'][] = [
'delete' => [
'_index' => 'novel',
'_id' => $id
]
];
}
//删除整个索引(⚠️ 不是删除文档)
$client->indices()->delete([
'index' => 'novel'
]);
return $client->bulk($params);
}
test2026-08-12 21:21
