composer install elasticsearch/elasticsearch:8.19
<?php
include "vendor/autoload.php";
use Elastic\Elasticsearch\ClientBuilder;
$esUrl = 'http://localhost:9200';
// 创建客户端
$client = ClientBuilder::create()
->setHosts([$esUrl])
// 无认证和SSL
// ->setBasicAuthentication('elastic', 'password copied during Elasticsearch start')
// ->setCABundle('path/to/http_ca.crt')
->build();
echo '<pre>';
// 测试客户端
//$response = $client->info();
//var_dump($response->asArray());
//var_dump($response->asObject()->version->number);
//var_dump($response->asBool());
//var_dump($response->asString());
//索引文档
//要索引一个文档,我们需要指定三件信息:索引、id和文档主体。
//这是通过构建一个键:值对的关联数组来完成的。
//请求主体本身也是一个关联数组,其中键:值对对应于文档中的数据:
//$params = [
// 'index' => 'my_index',
// 'id' => 'my_id',
// 'body' => ['testField' => 'abc'],
//];
//$response = $client->index($params);
//返回的响应表明文档是在您指定的索引中创建的。
//可以使用asArray()函数将响应渲染为关联数组。
//数组响应包含Elasticsearch返回的JSON的解码版本:
//print_r($response->asArray());
//将主体设置为JSON字符串
//如果你想,可以将`body`参数指定为JSON字符串。
//这在测试时(例如,从在线代码示例中复制和粘贴)或当你已经有要存储在Elasticsearch中的JSON文档时会很有用。
//例如,前面的索引示例可以重新编写如下:
//$params = [
// 'index' => 'my_index',
// 'id' => 'my_id',
// 'body' => '{"testField" : "abc"}',
//];
//$response = $client->index($params);
//print_r($response->asArray());
//获取文件
//让我们获取刚刚索引的文档。这将返回文档:
//$params = [
// 'index' => 'my_index',
// 'id' => 'my_id'
//];
//$response = $client->get($params);
//响应包含索引、版本等元数据以及一个 _source字段,该字段是您发送到Elasticsearch的原始文档。
//print_r($response->asArray());
//正在搜索文档
//搜索是Elasticsearch的标志,所以让我们进行一次搜索。我们将使用match查询作为演示:
//$params = [
// 'index' => 'my_index',
// 'body' => [
// 'query' => [
// 'match' => [
// 'testField' => 'abc'
// ]
// ]
// ]
//];
//$response = $client->search($params);
//这里的响应与之前的响应不同。您可以看到元数据 (took, timed_out, 等等.) 和一个名为 hits的数组。
//这代表了您的 搜索结果。在 hits内是另一个名为 hits的数组,其中包含 单独的搜索结果:
//print_r($response->asArray());
//删除文档
//$params = [
// 'index' => 'my_index',
// 'id' => 'my_id'
//];
//
//$response = $client->delete($params);
//print_r($response->asArray());
//删除索引
//由于Elasticsearch的动态特性,您添加的第一个文档会自动生成一个索引,并使用一些默认设置。
//稍后删除该索引并指定您自己的设置:
//$deleteParams = [
// 'index' => 'my_index'
//];
//$response = $client->indices()->delete($deleteParams);
//print_r($response->asArray());
//创建索引
//既然你正在从头开始(没有数据或索引),添加一个具有自定义设置的新索引:
//$params = [
// 'index' => 'my_index',
// 'body' => [
// 'settings' => [
// 'number_of_shards' => 2,
// 'number_of_replicas' => 0,
// ],
// ],
//];
//$response = $client->indices()->create($params);
//echo($response);