Query DSL

作者: 潘大的笔记 | 来源:发表于2019-08-08 11:41 被阅读0次

    请求体查询

    ……

    查询表达式

    ……

    查询与过滤

    如何选择查询和过滤?
    使用查询来进行全文搜索或是其它任何需要影响相关性得分的搜索。除此之外的情况都使用过滤

    最重要的查询

    1、match_all查询
    匹配所有文档,默认查询。通常和filter结合使用
    2、match查询
    标准的查询。
    全文字段使用,在执行查询前,它将用正确的分析器去分析查询字符串。
    {"match": {"tweet": "About Search" }}
    精确的字段使用,或者一个not_analyzed字符串字段,将会精确匹配。
    Tip:精确的查询应该使用filter(会被缓存)
    3、multi_match查询
    可以在多个字段上执行相同的match查询

    {
        "multi_match": {
            "query":    "full text search",
            "fields":   [ "title", "body" ]
        }
    }
    

    4、range查询
    找出那些落在指定区间内的数据或时间

    {
        "range": {
            "age": {
                "gte":  20,
                "lt":   30
            }
        }
    }
    

    操作符

    gt 大于
    gte 大于等于
    lt 小于
    lte 小于等于
    

    5、term查询
    精确值匹配,或not_analyzed的字符串。不分析文本
    6、terms查询
    与term类似,但是允许多值匹配。如果这个字段包含了指定字段值中的任何一个,那么就满足条件

    { "terms": { "tag": [ "search", "full_text", "nosql" ] }}
    

    7、exits查询和missing查询
    查找指定字段有值(exits)或者无值(missing)的文档

    {
        "exists":   {
            "field":    "title"
        }
    }
    

    组合多查询

    1、使用bool将查询组合起来

    must 必须匹配
    must_not 必须比匹配
    should 如果满足这些语句中的任意语句,将增加_score,否则无任何影响。主要用于修正每个文档的相关性得分
    filter 必须匹配,但它以不评分、过滤模式来进行
    
    {
        "bool": {
            "must":     { "match": { "title": "how to make millions" }},
            "must_not": { "match": { "tag":   "spam" }},
            "should": [
                { "match": { "tag": "starred" }},
                { "range": { "date": { "gte": "2014-01-01" }}}
            ]
        }
    }
    

    Tip:如果没有must语句,那么至少需要能够匹配其中一条should。
    2、带过滤器的查询
    上例中,如果不想引文文档的时间而影响得分的话,可以使用filter

    {
        "bool": {
            "must":     { "match": { "title": "how to make millions" }},
            "must_not": { "match": { "tag":   "spam" }},
            "should": [
                { "match": { "tag": "starred" }}
            ],
            "filter": {
              "range": { "date": { "gte": "2014-01-01" }} 
            }
        }
    }
    

    bool查询本身也可以用做不评分的查询(放在filter内)
    3、constant_score查询
    通常用于只需要执行一个filter,而没有其他查询的情况下
    可以用它来取代只有filter的bool查询,性能上是完全相同的

    {
        "constant_score":   {
            "filter": {
                "term": { "category": "ebooks" } 
            }
        }
    }
    

    term查询放置在constant_score转成不评分的filter。取代只有filter的bool查询

    验证查询

    验证查询是否合法

    GET /gb/tweet/_validate/query?explain
    {
       "query": {
          "tweet" : {
             "match" : "really powerful"
          }
       }
    }
    

    相关文章

      网友评论

          本文标题:Query DSL

          本文链接:https://www.haomeiwen.com/subject/yegtjctx.html