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

本章开始将介绍Elasticsearch DSL查询语法的复合查询。

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

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

  • constant_score query
  • bool query
  • dis_max query
  • function_score query
  • boosting query

本节目录

    • 1、constant_score query
    • 2、bool query
      • 2.1 过滤上下文(filter context)中查询对相关性(打分)的影响
    • 3、dis max query
    • 4、function score query(函数分数查询)
    • 5、boosting query

1、constant_score query

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

举例说明:(JAVA示例)

public static void testConstantScoreQuery() {
		RestHighLevelClient client = EsClient.getClient();
		try {
			SearchRequest searchRequest = new SearchRequest();
			searchRequest.indices("twitter");
			SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
			sourceBuilder.query(
					QueryBuilders.constantScoreQuery(QueryBuilders.wildcardQuery("user", "ding*"))
					.boost(1.5f)
			);
			searchRequest.source(sourceBuilder);
			SearchResponse result = client.search(searchRequest, RequestOptions.DEFAULT);
			System.out.println(result);
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			EsClient.close(client);
		}
	}

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

{                                                                    {
    "took":4,    														"took":2,
    "timed_out":false,													"timed_out":false,
    "_shards":{															"_shards":{
        "total":5,															"total":5,
        "successful":5,														"successful":5,
        "skipped":0,														"skipped":0,
        "failed":0															"failed":0
    },																	},
    "hits":{															"hits":{
        "total":1,															"total":1,
        "max_score":0.9808292,												"max_score":1.5,
        "hits":[															"hits":[
            {																	{
                "_index":"twitter",													"_index":"twitter",
                "_type":"_doc",														"_type":"_doc",
                "_id":"12",															"_id":"12",
                "_score":0.9808292,													"_score":1.5,
                "_source":{															"_source":{
                    "post_date":"2009-11-18T14:12:12",									"post_date":"2009-11-18T14:12:12",
                    "message":"test bulk",												"message":"test bulk",
                    "user":"dingw"														"user":"dingw"
                }																	}
            }																	}
        ]																	]
    }																	}
}																	}

2、bool query

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

字句类型 描述
must 该字句类型的查询语句,文档必须满足,并对评分产生影响(相关度)
filter 子句(查询)必须出现在匹配的文档中。然而,与must不同的是,查询的分数将被忽略。过滤器子句在过滤器上下文中执行,子句被考虑用于缓存。
should 应该匹配;如果没有must和filter,多个should只需要至少一个匹配即可,该数据可以通过参数minimum_should_match控制,如果包含了must或filter,则should不参与实际过滤,但会参与评分。
must_not 查询条件取反,及匹配到的文档必须不符合must_not的条件。

2.1 过滤上下文(filter context)中查询对相关性(打分)的影响

在过滤上下文环境的查询字句并不会对相关性产生影响,也就是说过滤上下文中的查询字句,返回的score为0。
例如如下查询示例(使用Java编写):

public static void testBoolQuery_filterContext_score() {
		RestHighLevelClient client = EsClient.getClient();
		try {
			SearchRequest searchRequest = new SearchRequest();
			searchRequest.indices("twitter");
			SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
			sourceBuilder.query(
					QueryBuilders.boolQuery()
											.filter(QueryBuilders.termQuery("user", "dingw"))
			);
			searchRequest.source(sourceBuilder);
			SearchResponse result = client.search(searchRequest, RequestOptions.DEFAULT);
			System.out.println(result);
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			EsClient.close(client);
		}
	}

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

{
    "took":4,
    "timed_out":false,
    "_shards":{
        "total":5,
        "successful":5,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":3,
        "max_score":0,
        "hits":[
            {
                "_index":"twitter",
                "_type":"_doc",
                "_id":"22",
                "_score":0,
                "_source":{
                    "post_date":"2018-10-31T14:12:10",
                    "message":"ab and hell",
                    "user":"dingw"
                }
            },
            {
                "_index":"twitter",
                "_type":"_doc",
                "_id":"12",
                "_score":0,
                "_source":{
                    "post_date":"2009-11-18T14:12:12",
                    "message":"test bulk",
                    "user":"dingw"
                }
            },
            {
                "_index":"twitter",
                "_type":"_doc",
                "_id":"11",
                "_score":0,
                "_source":{
                    "post_date":"2009-11-19T14:12:12",
                    "message":"test bulk update",
                    "user":"dingw"
                }
            }
        ]
    }
}

3、dis max query

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

	/**
	 * dis max query
	 */
	public static void testDisMaxQuery() {
		RestHighLevelClient client = EsClient.getClient();
		try {
			SearchRequest searchRequest = new SearchRequest();
			searchRequest.indices("twitter");
			SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
			sourceBuilder.query(
					QueryBuilders.disMaxQuery()
//										.tieBreaker(0.1f)
										.add(QueryBuilders.termQuery("user", "dingw").boost(1.2f))
										.add(QueryBuilders.termQuery("message", "bulk"))
			);
			searchRequest.source(sourceBuilder);
			SearchResponse result = client.search(searchRequest, RequestOptions.DEFAULT);
			System.out.println(result);
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			EsClient.close(client);
		}
	}

4、function score query(函数分数查询)

待研究。

5、boosting query

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

GET /_search
{
    "query": {
        "boosting" : {
            "positive" : {                                      // @1
                "term" : {
                    "field1" : "value1"
                }
            },
            "negative" : {                                // @2
                 "term" : {
                     "field2" : "value2"
                }
            },
            "negative_boost" : 0.2               
        }
    }
}

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

复合查询就介绍到这里了。

你可能感兴趣的:(Elasticsearch)