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是不會計算分數的。
示例:java

{
    "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去驗證一下搜索是否合法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便可spa

# 主要語法
"sort": [
    {
      "FIELD": {
        "order": "desc"
      }
    }
  ]
# 總體位置
GET /{index}/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "exists": {
          "field": ""
        }
      },
      "boost": 1.2
    }
  },
  "sort": [
    {
      "FIELD": {
        "order": "desc"
      }
    }
  ]
}
相關文章
相關標籤/搜索