<?php
include "vendor/autoload.php";
use Elastic\Elasticsearch\ClientBuilder;
$esUrl = 'http://127.0.0.1:9200';
// 创建客户端
$client = ClientBuilder::create()
->setHosts([$esUrl])
// 无认证和SSL
// ->setBasicAuthentication('elastic', 'password copied during Elasticsearch start')
// ->setCABundle('path/to/http_ca.crt')
->build();
echo '<pre>';
// 操作文档地址:https://www.elastic.co/guide/en/elasticsearch/client/php-api/8.19/search_operations.html#_match_query
$client = ClientBuilder::create()->build();
//搜索操作
$index = 'article';
//获取文档
$params = [
'index' => $index,
'id' => '1',
];
// Get doc at /my_index/_doc/my_id
//$response = $client->get($params);
//匹配查询
$params = [
'index' => $index,
'body' => [
'query' => [
'match' => [
'title' => '文章',
],
],
],
];
//$results = $client->search($params);
//使用原始JSON
$json = '{
"query" : {
"match" : {
"title" : "文章"
}
}
}';
$params = [
'index' => $index,
// 自动识别为json
'body' => $json,
];
//$results = $client->search($params);
// 搜索结果
//$milliseconds = $results['took'];
//$maxScore = $results['hits']['max_score'];
//$score = $results['hits']['hits'][0]['_score'];
//$doc = $results['hits']['hits'][0]['_source'];
//布尔查询
$params = [
'index' => $index,
'body' => [
'query' => [
'bool' => [
'must' => [
['match' => ['title' => '这是文章内容2']],
['term' => ['id' => '2']],
],
],
],
],
];
//$results = $client->search($params);
// 布尔查询复杂
$params = [
'index' => $index,
'body' => [
'query' => [
'bool' => [
'filter' => [
'term' => ['id' => '2'],
],
'should' => [
'match' => ['title' => '这是文章'],
],
],
],
],
];
//$results = $client->search($params);
$params = [
// 滚动请求之间的间隔时间。应该很小
'scroll' => '30s',
// 每个分片返回的结果数量
'size' => 50,
'index' => $index,
'body' => [
'query' => [
'match_all' => new \stdClass(),
],
],
];
// 执行搜索// 响应将包含第一批文档// 和一个 scroll_id
$response = $client->search($params);
// 现在我们循环直到滚动“光标”耗尽
while (isset($response['hits']['hits']) && count($response['hits']['hits']) > 0) {
// **// 在这里完成你的工作,处理 $response['hits']['hits'] 数组// **
print_r($response->asArray());
// 完成后,获取新的 scroll_id// 你必须始终刷新你的 _scroll_id! 它有时可能会改变
$scroll_id = $response['_scroll_id'];
// Execute a Scroll request and repeat
$response = $client->scroll([
'body' => [
'scroll_id' => $scroll_id,
'scroll' => '30s',
],
]);
}
//print_r($results->asArray());
PHP使用ES3搜索操作
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 1、抗拒学英文 在国内几乎所的编程语言都是外国的,所以学技术必定要学会看英文文档,如果不学英文,是绝对无法从菜鸟转...