elasticsearch學習筆記(二十七)——Elasticsearch filter與query

filter和query示例

PUT /employee/_doc/1
{
  "address": {
    "country": "china",
    "province": "jiangsu",
    "city": "nanjing"
  },
  "name": "tom",
  "age": 30,
  "join_date": "2016-01-01"
}
PUT /employee/_doc/2
{
  "address": {
    "country": "china",
    "province": "shanxi",
    "city": "xian"
  },
  "name": "marry",
  "age": 35,
  "join_date": "2015-01-01"
}

搜索請求:年齡必須大於等於30,同時join_date必須是2016-01-01緩存

GET /employee/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "join_date": "2016-01-01"
          }
        }
      ],
      "filter": {
        "range": {
          "age": {
            "gte": 30
          }
        }
      }
    }
  }
}
{
  "took" : 141,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "employee",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "address" : {
            "country" : "china",
            "province" : "jiangsu",
            "city" : "nanjing"
          },
          "name" : "tom",
          "age" : 30,
          "join_date" : "2016-01-01"
        }
      }
    ]
  }
}

filter與query對比大揭祕

filter:僅僅只是按照搜索條件過濾出須要的數據而已,比計算任何相關度分數,對相關度沒有任何影響

query: 會計算每一個document相對於搜索條件的相關度,並按照相關度進行排序

通常來講,若是是在進行搜索,須要將最匹配搜索條件的數據先返回,那麼用query。若是隻是要根據一些條件篩選出一部分數據,不關注其排序,那麼用filter。性能

filter與query性能對比

filter: 不須要計算相關度分數,不須要按照相關度分數進行排序,同時還有內置的自動緩存cache,會緩存住最常使用的filter數據

query: 須要計算相關度分數,並按照相關度分數進行排序,沒法緩存結果

相關文章
相關標籤/搜索