ES Query的一些小笔记

es query dsl

match_all 全查询

GET index/_search
{
  "query": {
    "match_all": {}
  }
}

match

匹配非字符串,精确查询
匹配字符串,模糊查询

GET index/_search
{
  "query": {
    "match": {
      "account_number": 995
    }
  }
}
---------------------------
GET index/_search
{
  "query": {
    "match": {
      "desc": "like me"
    }
  }
}

match_phrase

短句匹配,不分词匹配

GET index/_search
{
  "query": {
    "match_phrase": {
      "desc": "aaa bbb"
    }
  }
}
// 说明:只匹配含有aaa bbb的desc 

multi_match

多字段查询

GET index/_search
{
  "query": {
    "multi_match": {
      "query": "aaa bbb",
      "fields": [
        "desc",
        "name"
      ]
    }
  }
}
// 说明:在字段desc和name中查询含有"aaa bbb"的字符,只含有aaa的也能查询到
// 命中越多,评分越高

wildcard通配符匹配

对于keyword格式字段,是不会进行分词存储的,一般用来精准匹配,当需要模糊匹配时,可以使用通配符模糊匹配值

GET index/_search
{
   "query":{
        "wildcard":{
              	"desc":{
              		"value":"*test123*",
              		"boost":1 //权重设置,越大命中后分数越高
              	}
         }
    }
}

bool复合查询

bool是一个或多个查询字句的组合,可以理解为sql中 where a= ‘’ and b= ‘’,多个条件查询

  • must:必须匹配每个子查询,类似“与”
  • should:选择性匹配子查询,类似“或”
  • must_not:必须不匹配,不参与算分,类似“非”
  • filter:必须匹配,不参与算分

注: 查询时,参与打分字段越多,性能越低

1、must:必须符合

GET index/_search
{
   "query":{
        "bool":{
             "must":[
              {
              		"match_phrase":{
              			"desc":"aaa bbb"
              		}
              }
             ]
         }
    }
}
//说明:必须满足desc包含“aaa”和“age”=18

2、must_not:必须不符合

GET index/_search
{
   "query":{
        "bool":{
             "must_not":[
             	 {
             		 "match": {
             		 	"desc":"aaa"
             		 }
             	 }
             ]
         }
    }
}
//说明:必须t同时不满足desc包含“aaa”和“age”=18

3、should:应该满足,满足加分,不满足不加分

GET index/_search
{
   "query":{
        "bool":{
             "must":[
              {
              	"match":{
              		"desc":"aaa"
              		}
              	}
             ],
             "must_not": [
              {
                "match": {
                  "age": "18"
                }
              }
            ],
             "should": [
              {
                "match": {
                  "lastname": "Wallace"
                }
              }
            ]
         }
    }
}

4、filter结果过滤

GET index/_search
{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "balance": {
            "gte": "10000",
            "lte": "20000"
          }
        }
      }
    }
  }
}

term 非文本匹配

GET index/_search
{
  "query": {
    "term": {
      "age": 28
    }
  }
}

和match一样。匹配某个属性的值。全文检索字段用match,其他非text字段匹配用term。

原文链接:https://www.jianshu.com/p/9b013e563b08


版权声明:本文为weixin_49374214原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。