elasticsearch php实现
安装 Elasticsearch PHP 客户端
使用 Composer 安装官方提供的 Elasticsearch PHP 客户端库。在项目目录下运行以下命令:
composer require elasticsearch/elasticsearch
建立客户端连接
引入自动加载文件并创建 Elasticsearch 客户端实例:
require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()
->setHosts(['localhost:9200']) // 设置ES服务器地址
->build();
索引文档操作
创建新索引并添加文档:
$params = [
'index' => 'my_index',
'id' => '1',
'body' => ['title' => '测试文档', 'content' => '这是PHP插入的内容']
];
$response = $client->index($params);
搜索文档
执行基本搜索查询:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => ['title' => '测试']
]
]
];
$results = $client->search($params);
print_r($results['hits']['hits']);
更新文档
部分更新现有文档:
$params = [
'index' => 'my_index',
'id' => '1',
'body' => [
'doc' => ['content' => '更新后的内容']
]
];
$response = $client->update($params);
删除文档
删除指定文档:
$params = [
'index' => 'my_index',
'id' => '1'
];
$response = $client->delete($params);
批量操作
执行批量索引操作提高效率:
$params = ['body' => []];
$params['body'][] = [
'index' => [
'_index' => 'my_index',
'_id' => '2'
]
];
$params['body'][] = [
'title' => '批量文档1',
'content' => '批量内容1'
];
$params['body'][] = [
'index' => [
'_index' => 'my_index',
'_id' => '3'
]
];
$params['body'][] = [
'title' => '批量文档2',
'content' => '批量内容2'
];
$response = $client->bulk($params);
高级搜索功能
使用复合查询和聚合:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'bool' => [
'must' => [
['match' => ['title' => '测试']],
['range' => ['created_at' => ['gte' => 'now-1d/d']]]
]
]
],
'aggs' => [
'content_terms' => ['terms' => ['field' => 'content.keyword']]
]
]
];
错误处理
添加异常处理机制:
try {
$response = $client->search($params);
} catch (Elasticsearch\Common\Exceptions\Missing404Exception $e) {
echo "索引不存在: ".$e->getMessage();
} catch (Exception $e) {
echo "发生错误: ".$e->getMessage();
}
性能调优
配置客户端连接参数:
$client = Elasticsearch\ClientBuilder::create()
->setHosts(['127.0.0.1:9200'])
->setRetries(2) // 重试次数
->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool')
->setSelector('\Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector')
->build();






