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 = Elasticsearch\ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
创建索引
创建一个新的索引并定义映射:
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
],
'mappings' => [
'properties' => [
'title' => [
'type' => 'text'
],
'content' => [
'type' => 'text'
],
'timestamp' => [
'type' => 'date'
]
]
]
]
];
$response = $client->indices()->create($params);
添加文档
向索引中添加文档数据:

$params = [
'index' => 'my_index',
'id' => '1',
'body' => [
'title' => 'Test Document',
'content' => 'This is a test document for Elasticsearch.',
'timestamp' => '2023-01-01'
]
];
$response = $client->index($params);
搜索文档
执行搜索查询并获取结果:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'content' => 'test'
]
]
]
];
$response = $client->search($params);
print_r($response['hits']['hits']);
更新文档
更新索引中的文档:
$params = [
'index' => 'my_index',
'id' => '1',
'body' => [
'doc' => [
'content' => 'Updated content for the test document.'
]
]
];
$response = $client->update($params);
删除文档
从索引中删除文档:

$params = [
'index' => 'my_index',
'id' => '1'
];
$response = $client->delete($params);
删除索引
删除整个索引:
$params = [
'index' => 'my_index'
];
$response = $client->indices()->delete($params);
批量操作
执行批量操作以提高效率:
$params = [
'body' => [
['index' => [
'_index' => 'my_index',
'_id' => '2'
]],
['title' => 'Second Document', 'content' => 'Another test document.'],
['index' => [
'_index' => 'my_index',
'_id' => '3'
]],
['title' => 'Third Document', 'content' => 'Yet another test document.']
]
];
$response = $client->bulk($params);
聚合查询
执行聚合查询以获取数据分析结果:
$params = [
'index' => 'my_index',
'body' => [
'aggs' => [
'content_terms' => [
'terms' => [
'field' => 'content.keyword'
]
]
]
]
];
$response = $client->search($params);
print_r($response['aggregations']);
以上是 PHP 实现 Elasticsearch 的基本操作,包括索引管理、文档操作、搜索查询和聚合分析等功能。






