Elasticsearch-40-实战案例-组合多个filter搜索

之前我们有写过用bool来组合多个query,同样的bool也可以组合多个filter来搜索

基于bool组合多个filter搜索数据

需求一

搜索发帖日期为2017-01-01,或者帖子ID为XHDK-A-1293-#fJ3的帖子,同时要求帖子的发帖日期绝对不为2017-01-02

这个需求如果写为SQL的话就是:

1
2
3
4
SELECT * FROM forum.article 
where
(postDate='2017-01-01' or id ='XHDK-A-1293-#fJ3')
and postDate <> 2017-01-02

然后我们在es中组合一下搜索条件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
GET forum/article/_search
{
"query": {
"constant_score": {
"filter": {
"bool": {
"should":[
{
"term":{"postDate":"2017-01-01"}
},
{
"term":{"articleID":"XHDK-A-1293-#fJ3"}
}
],
"must_not":[
{
"term":{"postDate":"2017-01-02"}
}
]
}
}
}
}
}

返回数据:

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
{
"took": 61,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 1,
"hits": [
{
"_index": "forum",
"_type": "article",
"_id": "1",
"_score": 1,
"_source": {
"articleID": "XHDK-A-1293-#fJ3",
"userID": 1,
"hidden": false,
"postDate": "2017-01-01"
}
},
{
"_index": "forum",
"_type": "article",
"_id": "3",
"_score": 1,
"_source": {
"articleID": "JODL-X-1937-#pV7",
"userID": 2,
"hidden": false,
"postDate": "2017-01-01"
}
}
]
}
}

需求二

搜索帖子ID为XHDK-A-1293-#fJ3,或者是帖子ID为JODL-X-1937-#pV7而且发帖日期为2017-01-01的帖子

先来将需求转化为sql

1
2
3
4
5
SELECT * FROM forum.article 
where
id = 'XHDK-A-1293-#fJ3'
or
(id='JODL-X-1937-#pV7' and postDate = '2017-01-01')

然后在es中组合搜索条件

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
GET /forum/article/_search
{
"query": {
"constant_score": {
"filter": {
"bool": {
"should":[
{
"term":{
"articleID":"XHDK-A-1293-#fJ3"
}
},
{
"bool":{
"must":[
{
"term":{
"articleID":"JODL-X-1937-#pV7"
}
},
{
"term":{
"postDate":"2017-01-01"
}
}
]
}
}
]
}
}
}
}
}

返回值:

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
{
"took": 8,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 1,
"hits": [
{
"_index": "forum",
"_type": "article",
"_id": "1",
"_score": 1,
"_source": {
"articleID": "XHDK-A-1293-#fJ3",
"userID": 1,
"hidden": false,
"postDate": "2017-01-01"
}
},
{
"_index": "forum",
"_type": "article",
"_id": "3",
"_score": 1,
"_source": {
"articleID": "JODL-X-1937-#pV7",
"userID": 2,
"hidden": false,
"postDate": "2017-01-01"
}
}
]
}
}

总结
  • should: 可以匹配其中任意一个
  • must: 必须匹配
  • must_not: 必须不匹配