php实现es搜索
PHP 实现 Elasticsearch 搜索
Elasticsearch 是一个分布式搜索和分析引擎,支持全文搜索、结构化搜索和分析。在 PHP 中可以通过官方提供的 Elasticsearch PHP 客户端库实现与 Elasticsearch 的交互。
安装 Elasticsearch PHP 客户端
使用 Composer 安装 Elasticsearch PHP 客户端库:
composer require elasticsearch/elasticsearch
连接到 Elasticsearch
创建一个 PHP 脚本,初始化 Elasticsearch 客户端:
require 'vendor/autoload.php';
$client = Elastic\Elasticsearch\ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
索引文档
在 Elasticsearch 中存储数据前,需要先索引文档:
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => ['title' => 'Test Document', 'content' => 'This is a test document.']
];
$response = $client->index($params);
搜索文档
执行搜索查询,查找匹配的文档:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'title' => 'Test'
]
]
]
];
$response = $client->search($params);
print_r($response['hits']['hits']);
高级搜索
使用布尔查询组合多个条件:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'bool' => [
'must' => [
['match' => ['title' => 'Test']],
['match' => ['content' => 'document']]
]
]
]
]
];
$response = $client->search($params);
聚合查询
执行聚合操作,例如按字段分组统计:
$params = [
'index' => 'my_index',
'body' => [
'aggs' => [
'group_by_title' => [
'terms' => ['field' => 'title.keyword']
]
]
]
];
$response = $client->search($params);
print_r($response['aggregations']);
更新和删除文档
更新现有文档:
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => [
'doc' => ['content' => 'Updated content']
]
];
$response = $client->update($params);
删除文档:
$params = [
'index' => 'my_index',
'id' => 'my_id'
];
$response = $client->delete($params);
处理错误
捕获并处理 Elasticsearch 可能抛出的异常:
try {
$response = $client->search($params);
} catch (Elastic\Elasticsearch\Exception\ElasticsearchException $e) {
echo 'Error: ' . $e->getMessage();
}
性能优化
对于大量数据,使用批量操作提高效率:
$params = ['body' => []];
for ($i = 1; $i <= 100; $i++) {
$params['body'][] = [
'index' => [
'_index' => 'my_index',
'_id' => $i
]
];
$params['body'][] = [
'title' => 'Document ' . $i,
'content' => 'Content for document ' . $i
];
}
$response = $client->bulk($params);
通过以上方法,可以在 PHP 中实现基本的 Elasticsearch 搜索功能。根据具体需求,可以进一步探索 Elasticsearch 的高级查询和聚合功能。







