Elasticsearch-PHP 客户端连接与基础操作指南
前言
Elasticsearch-PHP 是 Elasticsearch 官方提供的 PHP 客户端库,它允许 PHP 开发者与 Elasticsearch 集群进行交互。本文将详细介绍如何连接 Elasticsearch 集群以及基本的 CRUD 操作。
连接 Elasticsearch 集群
1. 连接 Elastic Cloud
Elastic Cloud 是 Elastic 公司提供的托管服务,连接它需要两个关键信息:
- Cloud ID:唯一标识你的 Elastic Cloud 部署
- API Key:用于身份验证的安全密钥
$client = ClientBuilder::create()
->setElasticCloudId('<你的 Cloud ID>')
->setApiKey('<你的 API Key>')
->build();
安全提示:API Key 一旦生成后无法再次查看,请务必妥善保存。
2. 本地安全连接(HTTPS)
Elasticsearch 8.0 及以上版本默认启用安全功能,使用 TLS 加密通信。连接时需要:
- 获取 CA 证书文件 (
http_ca.crt
) - 使用 elastic 用户及其密码
$client = ClientBuilder::create()
->setHosts(['https://localhost:9200'])
->setBasicAuthentication('elastic', '你的密码')
->setCABundle('/path/to/http_ca.crt')
->build();
Docker 用户注意:运行 Elasticsearch 容器时,密码和 CA 证书会自动生成,请从终端输出中获取。
基础操作指南
1. 获取集群信息
使用 info()
方法获取 Elasticsearch 实例的基本信息:
$response = $client->info();
响应对象支持多种访问方式:
- 作为 PSR-7 响应对象
- 作为数组
- 作为对象
// 作为数组访问
echo $response['version']['number'];
// 作为对象访问
echo $response->version->number;
2. 文档操作
索引文档(创建/更新)
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
JSON 字符串支持:body 参数可以直接使用 JSON 字符串:
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => '{"testField":"abc"}'
];
获取文档
$params = [
'index' => 'my_index',
'id' => 'my_id'
];
$response = $client->get($params);
响应中包含元数据和原始文档内容 (_source
字段)。
搜索文档
使用 match 查询示例:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
$response = $client->search($params);
响应包含搜索结果的 hits 数组和相关元数据。
删除文档
$params = [
'index' => 'my_index',
'id' => 'my_id'
];
$response = $client->delete($params);
3. 索引管理
删除索引
$params = ['index' => 'my_index'];
$response = $client->indices()->delete($params);
创建索引
创建带有自定义设置的索引:
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
]
]
];
$response = $client->indices()->create($params);
最佳实践
- 连接管理:建议复用客户端实例,避免频繁创建新连接
- 错误处理:所有操作都应包含 try-catch 块处理可能的异常
- 安全存储:敏感信息如 API Key 和密码应使用安全的方式存储
- 性能考虑:批量操作时使用 bulk API 提高效率
总结
本文介绍了 Elasticsearch-PHP 客户端的基本使用方法,包括连接 Elasticsearch 集群的各种方式以及基础的 CRUD 操作。掌握这些基础知识后,你可以开始构建更复杂的搜索和分析功能。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考