elasticsearch学习笔记(二十八)——Elasticsearch 实战各种query搜索

各种query搜索语法

match_all

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

match

GET /{index}/_search
{
  "query": {
    "match": {
      "FIELD": "TEXT"
    }
  }
}

multi match

GET /{index}/_search
{
  "query": {
    "multi_match": {
      "query": "",
      "fields": []
    }
  }
}

range query

GET /{index}/_search
{
  "query": {
    "range": {
      "FIELD": {
        "gte": 10,
        "lte": 20
      }
    }
  }
}

term query

GET /{index}/_search
{
  "query": {
    "term": {
      "FIELD": {
        "value": "VALUE"
      }
    }
  }
}

terms query

GET /{index}/_search
{
  "query": {
    "terms": {
      "FIELD": [
        "VALUE1",
        "VALUE2"
      ]
    }
  }
}

exist query

GET /{index}/_search
{
  "query": {
    "exists": {
       "field": ""
    }
  }
}

多搜索条件组合查询

bool: must, must_not, should, filter

每个子查询都会计算一个document针对它的相关度分数,然后bool综合所有分数,合并为一个分数,当然filter是不会计算分数的。
示例:

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

GET /{index}/_search
{
  "query": {
    "constant_score": {
      "filter": {},
      "boost": 1.2
    }
  }
}

定位不合法的搜索

一般用在那种特别复杂庞大的搜索下,比如你一下子写上了上百行的搜索,这个时候可以先用validate api去验证一下搜索是否合法

GET /employee/_validate/query?explain
{
  "query": {
    "constant_score": {
      "filter": {},
      "boost": 1.2
    }
  }
}
{
  "valid" : false,
  "error" : "ParsingException[Failed to parse]; nested: IllegalArgumentException[query malformed, empty clause found at [4:18]];; java.lang.IllegalArgumentException: query malformed, empty clause found at [4:18]"
}
GET /employee/_validate/query?explain
{
  "query": {
    "constant_score": {
      "filter": {
        "term": {
          "name": "tom"
        }
      },
      "boost": 1.2
    }
  }
}
{
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "valid" : true,
  "explanations" : [
    {
      "index" : "employee",
      "valid" : true,
      "explanation" : "(ConstantScore(name:tom))^1.2"
    }
  ]
}

定制搜索结果的排序规则

默认情况下,返回的document是按照_score降序排列的。如果我们想自己定义排序规则怎么办,此时只需要使用sort即可

# 主要语法
"sort": [
    {
      "FIELD": {
        "order": "desc"
      }
    }
  ]
# 整体位置
GET /{index}/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "exists": {
          "field": ""
        }
      },
      "boost": 1.2
    }
  },
  "sort": [
    {
      "FIELD": {
        "order": "desc"
      }
    }
  ]
}

相关推荐