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

Stella981
• 阅读 681

本文将重点介绍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" : {                                // @211                 "term" : {12                     "field2" : "value2"13                }14            },15            "negative_boost" : 0.2               16        }17    }18}                                                            }

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


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

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

本文分享自微信公众号 - 中间件兴趣圈(dingwpmz_zjj)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Stella981 Stella981
3年前
Elasticsearch Query DSL概述与查询、过滤上下文
从本节开始,先详细介绍ElasticsearchQueryDSL语法,该部分是SearchAPI的核心基础之一。Elasticsearch提供了一个基于JSON的完整查询DSL(领域特定语言)来定义查询。把查询DSL看作是查询的AST(抽象语法树),由两种类型的子句组成:Leafqueryclauses(叶查询字句)叶子
Wesley13 Wesley13
3年前
MySQL总结(十一)子查询
!(https://oscimg.oschina.net/oscnet/upa344f41e81d3568e3310b5da00c57ced8ea.png)子查询1\.什么是子查询需求:查询开发部中有哪些员工selectfromemp;通
Wesley13 Wesley13
3年前
Oracle——分页查询
查询员工表中,工资排名在1020之间的员工信息。select  from(    selectrownumrn,employee_id,salary      from(        selectemployee_id,salary,last_name        fromem
Wesley13 Wesley13
3年前
mysql5.6 分页查询优化
mysql5.6分页查询优化场景:表结构:主键(非自增)contentCode(varchar),过滤条件列为updateTime(timeStamp),已经为timestamp建立索引。搜索sql为:SELECTFROMmy_hello_tableWHEREupdat
Wesley13 Wesley13
3年前
oracle查询表数据并重新插入到本表
oracle查询表数据并重新插入到本表CreateTime2018年5月17日10:30:10Author:Marydon1.情景描述查询表中数据SELECTFROMat_aut
Wesley13 Wesley13
3年前
mysql数据库的查询
1、“查”——之单表查询INSERTINTOstudent2(name,grade,gender)VALUES('songjiang',40,'男'),('wuyong',100,'男'),('qinming',90,'男'),('husanniang',88,'女'),('sunerniang',66,'女'),('wus
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Stella981 Stella981
3年前
ELK学习笔记之ElasticSearch的索引详解
0x00ElasticSearch的索引和MySQL的索引方式对比Elasticsearch是通过Lucene的倒排索引技术实现比关系型数据库更快的过滤。特别是它对多条件的过滤支持非常好,比如年龄在18和30之间,性别为女性这样的组合查询。倒排索引很多地方都有介绍,但是其比关系型