PHP中使用ElasticSearch
<?php
require 'vendor/autoload.php'; // 确保通过Composer安装了Elasticsearch-PHP客户端
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,
'about' => 'I love to go rock climbing'
]
];
$response = $client->index($params);
// 搜索文档
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'about' => 'climbing'
]
]
]
];
$response = $client->search($params);
print_r($response); // 打印搜索结果
?>
这段代码展示了如何在PHP中使用Elasticsearch-PHP客户端库来执行基本的Elasticsearch操作,包括创建索引、添加文档和执行搜索。代码中使用了Elasticsearch的参数化查询,这是一种安全、易于维护的方式来与Elasticsearch交互。
评论已关闭