查看原文
其他

Elasticsearch Query DSL之Compound queries(复合查询)

丁威 中间件兴趣圈 2022-11-10

本文将重点介绍Elasticsearch Query DSL之Compound queries(复合查询)。

复合查询概述

复合查询将其他复合查询或叶子查询进行包装,组合它们的结果和分数,以此改变它们的行为,或从查询字句切换到过滤上下文模式。

主要的复合查询包括如下:

  • constant_score query

  • bool query

  • dis_max query

  • function_score query

  • boosting query

constant_score query

常量(score)评分查询,该复合查询将忽略文档本身的匹配相关性评分,而是统一返回请求参数的boost。实例如下(Java):

1public static void testConstantScoreQuery() {
2        RestHighLevelClient client = EsClient.getClient();
3        try {
4            SearchRequest searchRequest = new SearchRequest();
5            searchRequest.indices("twitter");
6            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
7            sourceBuilder.query(
8                    QueryBuilders.constantScoreQuery(QueryBuilders.wildcardQuery("user", "ding*"))
9                    .boost(1.5f)
10            );
11            searchRequest.source(sourceBuilder);
12            SearchResponse result = client.search(searchRequest, RequestOptions.DEFAULT);
13            System.out.println(result);
14        } catch (Throwable e) {
15            e.printStackTrace();
16        } finally {
17            EsClient.close(client);
18        }
19    }

返回的结果为:为了对比,左边的结果是Qu-eryBuilders.wildcardQuery("user", "ding*")查询,而右边的是constant_score (复合查询)。

1{                                                                    {
2    "took":4,                                                            "took":2,
3    "timed_out":false,                                                    "timed_out":false,
4    "_shards":{                                                            "_shards":{
5        "total":5,                                                            "total":5,
6        "successful":5,                                                        "successful":5,
7        "skipped":0,                                                        "skipped":0,
8        "failed":0                                                            "failed":0
9    },                                                                    },
10    "hits":{                                                            "hits":{
11        "total":1,                                                            "total":1,
12        "max_score":0.9808292,                                                "max_score":1.5,
13        "hits":[                                                            "hits":[
14            {                                                                    {
15                "_index":"twitter",                                                    "_index":"twitter",
16                "_type":"_doc",                                                        "_type":"_doc",
17                "_id":"12",                                                            "_id":"12",
18                "_score":0.9808292,                                                    "_score":1.5,
19                "_source":{                                                            "_source":{
20                    "post_date":"2009-11-18T14:12:12",                                    "post_date":"2009-11-18T14:12:12",
21                    "message":"test bulk",                                                "message":"test bulk",
22                    "user":"dingw"                                                        "user":"dingw"
23                }                                                                    }
24            }                                                                    }
25        ]                                                                    ]
26    }                                                                    }
27}                                                                    }

bool query

布尔查询。bool query里能包含的主要子句类型如下:

  • must
    该字句类型的查询语句,文档必须满足,并对评分产生影响(相关度)

  • filter
    子句(查询)必须出现在匹配的文档中。然而与must不同的是查询的分数将被忽略。过滤器子句在过滤器上下文中执行,子句被考虑用于缓存。

  • should
    应该匹配;如果没有must和filter,多个s-hould只需要至少一个匹配即可,该数据可以通过参数minimum_should_match控制,如果包含了must或filter,则should不参与实际过滤,但会参与评分。

  • must_not
    查询条件取反,及匹配到的文档必须不符合must_not的条件。

filter context中查询对相关性的影响

在过滤上下文环境的查询字句并不会对相关性产生影响,也就是说过滤上下文中的查询子句返回的score为0。

例如如下查询示例(使用Java编写):

1public static void testBoolQuery_filterContext_score() {
2        RestHighLevelClient client = EsClient.getClient();
3        try {
4            SearchRequest searchRequest = new SearchRequest();
5            searchRequest.indices("twitter");
6            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
7            sourceBuilder.query(
8                    QueryBuilders.boolQuery()
9                                            .filter(QueryBuilders.termQuery("user", "dingw"))
10            );
11            searchRequest.source(sourceBuilder);
12            SearchResponse result = client.search(searchRequest, RequestOptions.DEFAULT);
13            System.out.println(result);
14        } catch (Throwable e) {
15            e.printStackTrace();
16        } finally {
17            EsClient.close(client);
18        }
19    }                                                                   }

其返回的结果,其score都为0,结果如下:

1public static void testBoolQuery_filterContext_score() {
2        RestHighLevelClient client = EsClient.getClient();
3        try {
4            SearchRequest searchRequest = new SearchRequest();
5            searchRequest.indices("twitter");
6            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
7            sourceBuilder.query(
8                    QueryBuilders.boolQuery()
9                                            .filter(QueryBuilders.termQuery("user", "dingw"))
10            );
11            searchRequest.source(sourceBuilder);
12            SearchResponse result = client.search(searchRequest, RequestOptions.DEFAULT);
13            System.out.println(result);
14        } catch (Throwable e) {
15            e.printStackTrace();
16        } finally {
17            EsClient.close(client);
18        }
19    }                                                                   }

dis max query

该查询方式将所有查询字句进行联合查询(uni-oion)只需要其中一个条件匹配则返回文档,但在计算相关性时不是将所有条件的匹配度(
score)相加,而是使用评分最高的查询条件的score;如果有指定tie_breaker的话,则为最大score 加上 其他score * tie_breaker。dis max query是实现(match query multi fields best_-fields)的核心。每个查询可以指定其评分因子(权重、boost)、dis max query使用示例:

1/**
2     * dis max query
3     */
4    public static void testDisMaxQuery() {
5        RestHighLevelClient client = EsClient.getClient();
6        try {
7            SearchRequest searchRequest = new SearchRequest();
8            searchRequest.indices("twitter");
9            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
10            sourceBuilder.query(
11                    QueryBuilders.disMaxQuery()
12//                                        .tieBreaker(0.1f)
13                                        .add(QueryBuilders.termQuery("user", "dingw").boost(1.2f))
14                                        .add(QueryBuilders.termQuery("message", "bulk"))
15            );
16            searchRequest.source(sourceBuilder);
17            SearchResponse result = client.search(searchRequest, RequestOptions.DEFAULT);
18            System.out.println(result);
19        } catch (Throwable e) {
20            e.printStackTrace();
21        } finally {
22            EsClient.close(client);
23        }
24    }                                                               }

function score query

函数分数查询,暂不深入学习。

boosting query

boosting query可以用来提升或降低某些查询条件的权重。举例如下:

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


代码@1:积极的作用,提升其权重。
代码@2:负面的影响,希望降低其权重,其权重值通过negative_boost指定。


更多文章请关注微信公众号:


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存