0%

elasticsearch复杂查询

elasticsearch复杂查询

有时候查询语句会非常复杂,这时候肯定只能使用DSL查询了,使用各个简单子句合并成一个复杂的查询语句

查询DSL的格式为

  • 查询:以query参数开始,用于检查内容与条件是否匹配
  • 过滤:以filter参数开始,不计算匹配得分,只是简单的决定文档是否匹配,主要用于过滤结构化数据
  • 叶查询子句:在特定的字段上查找特定的值,如match,term 和range
  • 复合查询子句:包含其他叶查询或复合查询子句,以合理的方式结合多条查询,如bool或dis_max查询,或者改变查询行为,如constant_score查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"bool":{ // 合并多个条件的布尔逻辑
"must":{ // 多个查询条件完全匹配,相当于and
"match":{
"field":""
}
},
"must_not":{ // 多个查询条件都不匹配,相当于not
"match":{
"field":""
}
},
"should":{ // 有一个条件匹配,相当于or
"match":{
"field":""
}
}
}
}

bool查询

获取匹配其他查询的布尔值的文档,基于一个或多个布尔子句使用

  • must 必须出现在匹配文档中,且影响匹配得分,相当于AND
  • filter 必须出现在匹配文档中,与must功能相同,只是不评分,只进行过滤
  • should 应该出现在匹配文档中,如果没有must或filter子句,则必须匹配一个或多个should子句,匹配的最小数量可以使用minimum_should_match来进行设置,相当于OR
  • must_not 必须不能出现在匹配文档中,相当于not
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"query": {
"bool" : {
"must" : {
"term" : { "user" : "kimchy" }
},
"filter": {
"term" : { "tag" : "tech" }
},
"must_not" : {
"range" : {
"age" : { "gte" : 10, "lte" : 20 }
}
},
"should" : [
{ "term" : { "tag" : "wow" } },
{ "term" : { "tag" : "elasticsearch" } }
],
"minimum_should_match" : 1,
"boost" : 1.0
}
}
}

最大值获取

通过执行子查询生成文档的并集,执行查询的最大匹配得分作为文档得分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"query": {
"dis_max" : {
"tie_breaker" : 0.7,
"boost" : 1.2,
"queries" : [
{
"term" : { "age" : 34 }
},
{
"term" : { "age" : 35 }
}
]
}
}
}

boosting查询

用来有效降级匹配给出的查询结果,仍然包含不符合条件的文档,但是降低得分

包括positive、negative、negative_boost三部分,positive中的查询评分保持不变,negative中的查询会降低文档评分,negative_boost指明negative中降低的权值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"query": {
"boosting" : {
"positive" : {
"term" : {
"field1" : "value1"
}
},
"negative" : {
"term" : {
"field2" : "value2"
}
},
"negative_boost" : 0.2
}
}
}

欢迎关注我的其它发布渠道