ElasticSearch与PHP的集成:如何使用PHP与ElasticSearch进行交互
<?php
require 'vendor/autoload.php'; // 引入composer的自动加载文件
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->setHosts(['localhost:9200'])->build(); // 创建ElasticSearch客户端
// 创建索引操作
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_shards' => 5,
'number_of_replicas' => 1
]
]
];
$response = $client->indices()->create($params);
// 添加文档操作
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => ['name' => 'John Doe', 'age' => 30]
];
$response = $client->index($params);
// 搜索文档操作
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'name' => 'John'
]
]
]
];
$response = $client->search($params);
print_r($response); // 打印搜索结果
?>
这段代码展示了如何使用Elasticsearch-PHP客户端库与Elasticsearch进行交互。首先,我们创建了一个Elasticsearch客户端,然后执行了创建索引、添加文档和搜索文档的操作。最后,我们打印了搜索结果。这个例子简单明了地展示了如何在PHP中使用Elasticsearch。
评论已关闭