​​​​ php Elasticsearch记录 | 苏生不惑的博客

php Elasticsearch记录

安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
composer require "elasticsearch/elasticsearch:~5.0"
根据安装的版本来安装 https://packagist.org/packages/elasticsearch/elasticsearch
use Elasticsearch\ClientBuilder;
$host = xxx;
$port = xxx;
$hosts = [$host.':'.$port];
$client = ClientBuilder::create() // 实例化 ClientBuilder
->setHosts($hosts) // 设置主机信息
->build();
$params = [
'index' => xxx,
'type' => xxx,
'body' => [
'query' => [
'bool' => [
'must' => [
//['match'=>['id'=>274100]],
],
]
],
'sort'=> ['time' => 'desc'],
],

'size'=>100
];
查询所有
$response = $client->search($params);
took: 2,
timed_out: false,
_shards:- {
total: 6,
successful: 6,
failed: 0
},
hits:- {
total: 280015,
max_score: null,
hits:- [
-{
_index: "weibo",
_type: "wb",
_id: "2800",
_score: null,
_source:- {
id: 2800,
mid: "451247565335367",
is_top: 0,
tags:[],
time: "2020-06-05 15:18:16"
},
sort:- [
1591370296000
]
}
$match = [];
$not = [];
if ($params['is_top']){
$match[] = ['term'=>['is_top'=>$params['is_top']]];
}
if ($params['tag'] == 1){
$match[] = ['exists'=>['field'=>'tags']];//tags不为空
}
if ($params['start_time'] && $params['end_time'] && $params['end_time'] > $params['start_time']){
$match[] = ['range'=>['wb_time' => ['gte'=>$params['start_time'], 'lte'=> $params['end_time']]]];
}
if ($params['tag'] == 0){
$not[] = ['exists'=>['field'=>'tags']];//tags为空
}
$must = [['terms'=>['is_top'=>1]]];
if ($match){
$must = array_merge($must,$match);
}
if ($params['tags']){
$must[] = ['query_string'=>['fields'=>['tags'],'query'=>'*微博*']];//like
}
$search = [
'index' => xxx,
'type' => xxx,
'body' => [
'query' => [
'bool' => [
'must' => $must,
'must_not'=>$not,
],
],
'sort'=> ['time' => 'desc']
],
'from' => 1,
'size' => 10,
];
$response = $client->search($search);

笔记二十:Query & Filtering 与 多字符串多字段查询

中文文档

PHP DSL 查修构造器扩展

Elasticsearch: 权威指南