ES查询DSL之复合查询

复合查询

bool 查询

组合查询,组合多个查询类型

类型 说明 计分
must 字句必须出现在文档中
filter 字句必须匹配,如:status=1,在filter上下文中执行,不参与计分
should 字句应该出现在文档中
must_not 字句不得出现在文档中,在filter上下文中执行

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
"query": {
"bool": {
"must": [
{ "match": { "name": "液" }},
{ "match": { "productGeneralName": "液" }}
],
"filter": [
{ "term": { "status": "1" }}
],
"should":[{
"term": {"name": "太极"}
},{
"term":{"name":"哟西"}
}
],
"must_not": [
{"match": {
"name": "筋骨"
}}
]
}
}
}

结果:

bool采用“更好匹配”的原则,匹配条件越多的分数越高越靠前,must或should子句的得分将加在一起,通过_score返回最终得分,filter上下文中执行的条件(filter和must_not)得分为0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"query": {
"bool": {

"filter": [
{ "term": { "status": "1" }}
],
"must_not": [
{"match": {
"name": "阿莫西林"
}}
]
}
}
}

以上结果得分为0:

Boosting 查询

通过一定规则来影响得分,可以使用boosting查询来降级某些文档,而不必将它们从搜索结果中排除

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"query": {
"boosting" : {
"positive" : {
"term" : {
"text" : "apple"
}
},
"negative" : {
"term" : {
"text" : "pie"
}
},
"negative_boost" : 0.5
}
}
}

  • positive(必需):正向激励,查询出包含”apple”的数据。
  • negative(必需):负向激励,降低包含”pie”的得分,但不会排除
  • negative_boost(必需):降低得分的比重

    假如positive返回的数据得分为2,negative匹配后会将2*0.5 = 1,所以最终得分1,以此降低包含“pie”数据的得分

Constant score 查询(固定得分查询)

包装filter查询(filter的默认得分是0),给匹配的文档赋一个固定的得分

1
2
3
4
5
6
7
8
9
10
{
"query": {
"constant_score" : {
"filter" : {
"term" : { "user" : "kimchy"}
},
"boost" : 1.2
}
}
}
  • filter(必需):用于过滤出文档
  • boost(可选,默认1.0): 设置的固定得分

Disjunction max query(最佳匹配查询 or 分离最大化查询)

将任何与任一查询匹配的文档作为结果返回,但只将最佳匹配的评分作为查询的评分结果返回,也就是返回最高的一个得分

例:

1
2
3
4
5
6
7
8
9
10
11
{
"query": {
"dis_max" : {
"queries" : [
{ "term" : { "title" : "Quick pets" }},
{ "term" : { "body" : "Quick pets" }}
],
"tie_breaker" : 0.7
}
}
}

  • queries(必需的查询对象数组):包含一个或多个查询子句,并返回匹配分最高的一个得分
  • tie_breaker(可选):值是一个浮点数(0~1.0),该参数的作用是将除最高分外其他几个条件的匹配得分也考虑进去。例如:值为0.2,那么 最终得分= 最高分 + 其他得分 * 0.2

参考链接:https://www.elastic.co/guide/cn/elasticsearch/guide/current/_best_fields.html#_best_fields

Function score 查询 (功能得分查询)

就是为返回的结果计算一个新的得分,包含一个查询和一个或多个函数,这些函数为每个返回的文档计算一个新得分。也能用过滤器对结果的子集 应用不同的函数

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"query": {
"function_score": {
"query": { "match": {
"name": "太极"
} },
"functions": [
{
"filter": {"match":{"name":"液"}},
"random_score": {}
},
{
"filter": {"match":{"name":"通天"}},
"weight": 50
}
],
"score_mode":"multiply"
}
}
}

如果没有给函数提供过滤器,则等同于指定 “match_all”: {}

  • score_mode:指定如何组合计算出的分数
取值 说明
multiply 分数相乘(默认)
sum 分数相加
avg 分数求平均值
first 具有匹配过滤器的第一个函数被应用
max 使用最高分
min 使用最低分数

太多了,脑壳痛,参考链接:https://www.elastic.co/guide/en/elasticsearch/reference/7.3/query-dsl-function-score-query.html