天天看點

ElasticSearch系列——基于bool組合多個filter條件來搜尋資料

文章目錄

        • 準備插入一些測試文章資料
          • 搜尋發帖日期為2017-01-01,或者文章ID為XHDK-A-1293-#fJ3的文章,同時要求文章的發帖日期絕對不為2017-01-02
        • 為文章資料增加tag字段
          • 搜尋tag中包含java的文章
          • 優化搜尋結果,僅僅搜尋tag隻包含java的文章

ElasticSearch系列——主目錄

準備插入一些測試文章資料

POST /forum/article/_bulk
{ "index": { "_id": 1 }}
{ "articleID" : "XHDK-A-1293-#fJ3", "userID" : 1, "hidden": false, "postDate": "2017-01-01" }
{ "index": { "_id": 2 }}
{ "articleID" : "KDKE-B-9947-#kL5", "userID" : 1, "hidden": false, "postDate": "2017-01-02" }
{ "index": { "_id": 3 }}
{ "articleID" : "JODL-X-1937-#pV7", "userID" : 2, "hidden": false, "postDate": "2017-01-01" }
{ "index": { "_id": 4 }}
{ "articleID" : "QQPX-R-3956-#aD8", "userID" : 2, "hidden": true, "postDate": "2017-01-02" }
           

結果顯示

ElasticSearch系列——基于bool組合多個filter條件來搜尋資料
搜尋發帖日期為2017-01-01,或者文章ID為XHDK-A-1293-#fJ3的文章,同時要求文章的發帖日期絕對不為2017-01-02
GET /forum/article/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "should": [
            {"term": { "postDate": "2017-01-01" }},
            {"term": {"articleID": "XHDK-A-1293-#fJ3"}}
          ],
          "must_not": {
            "term": {
              "postDate": "2017-01-02"
            }
          }
        }
      }
    }
  }
}
           

結果顯示

ElasticSearch系列——基于bool組合多個filter條件來搜尋資料

must,should,must_not,filter:必須比對,可以比對其中任意一個即可,必須不比對

term:是代表完全比對,也就是精确查詢,搜尋前不會再對搜尋詞進行分詞

constant_score: 當我們不關心檢索詞頻率TF(Term Frequency)對搜尋結果排序的影響時,可以使用constant_score将查詢語句query或者過濾語句filter包裝起來

為文章資料增加tag字段

POST /forum/article/_bulk
{ "update": { "_id": "1"} }
{ "doc" : {"tag" : ["java", "hadoop"]} }
{ "update": { "_id": "2"} }
{ "doc" : {"tag" : ["java"]} }
{ "update": { "_id": "3"} }
{ "doc" : {"tag" : ["hadoop"]} }
{ "update": { "_id": "4"} }
{ "doc" : {"tag" : ["java", "elasticsearch"]} }
           
ElasticSearch系列——基于bool組合多個filter條件來搜尋資料
搜尋tag中包含java的文章
GET /forum/article/_search
{
    "query" : {
        "constant_score" : {
            "filter" : {
                "terms" : { 
                    "tag" : ["java"]
                }
            }
        }
    }
}
           

結果顯示

ElasticSearch系列——基于bool組合多個filter條件來搜尋資料
優化搜尋結果,僅僅搜尋tag隻包含java的文章

先寫入

POST /forum/article/_bulk
{ "update": { "_id": "1"} }
{ "doc" : {"tag_cnt" : 2} }
{ "update": { "_id": "2"} }
{ "doc" : {"tag_cnt" : 1} }
{ "update": { "_id": "3"} }
{ "doc" : {"tag_cnt" : 1} }
{ "update": { "_id": "4"} }
{ "doc" : {"tag_cnt" : 2} }
           

在查詢

GET /forum/article/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "tag_cnt": 1
              }
            },
            {
              "terms": {
                "tag": ["java"]
              }
            }
          ]
        }
      }
    }
  }
}
           

結果顯示

ElasticSearch系列——基于bool組合多個filter條件來搜尋資料

繼續閱讀