elasticsearch php实现
使用 PHP 实现 Elasticsearch
Elasticsearch 是一个分布式搜索和分析引擎,PHP 可以通过官方客户端库与 Elasticsearch 交互。以下是实现方法:
安装 Elasticsearch PHP 客户端
通过 Composer 安装官方客户端库:
composer require elasticsearch/elasticsearch
连接 Elasticsearch 服务
创建客户端实例并连接到 Elasticsearch 服务:
require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
索引文档
将数据存入 Elasticsearch 索引:
$params = [
'index' => 'my_index',
'id' => '1',
'body' => ['title' => 'Test document', 'content' => 'This is a test']
];
$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',
'id' => '1',
'body' => [
'doc' => ['content' => 'Updated 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' => 'Another document',
'content' => 'Batch operation test'
];
$response = $client->bulk($params);
处理结果
检查操作是否成功并处理返回数据:
if ($response['_shards']['successful'] >= 1) {
echo "Operation succeeded";
} else {
echo "Operation failed";
}
异常处理
捕获并处理可能出现的异常:
try {
$response = $client->search($params);
} catch (Elasticsearch\Common\Exceptions\Missing404Exception $e) {
echo "Document not found";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
高级查询
使用更复杂的查询条件:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'bool' => [
'must' => [
['match' => ['title' => 'test']],
['range' => ['created_at' => ['gte' => '2023-01-01']]]
]
]
]
]
];
聚合查询
执行数据分析聚合:
$params = [
'index' => 'my_index',
'body' => [
'aggs' => [
'popular_terms' => [
'terms' => ['field' => 'title.keyword']
]
]
]
];
索引管理
创建和管理索引:
$params = [
'index' => 'new_index',
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 1
]
]
];
$response = $client->indices()->create($params);
以上代码示例展示了 PHP 与 Elasticsearch 交互的基本方法,包括 CRUD 操作、搜索、批量处理和索引管理。根据实际需求可以扩展更多功能。







