1. 程式人生 > 其它 >Elasticsearch 論壇實戰-基於bool組合多個filter條件來搜尋資料

Elasticsearch 論壇實戰-基於bool組合多個filter條件來搜尋資料

技術標籤:Elasticsearch實戰elasticsearch

Elasticsearch實戰

準備資料

PUT /forum/post/_bulk
{"index":{"_id":1}}
{"id":"XHDK-A-1293-#fJ3","userId":1,"postDate":"2020-12-16","hidden":true}
{"index":{"_id":2}}
{"id":"XGFJ-A-1273-#fJ3","userId":2,"postDate":"2020-12-15","hidden":false}
{"index":{"_id":3}}
{"id":"AHFS-A-2393-#ad5","userId":3,"postDate":"2020-11-05","hidden":false}
{"index":{"_id":4}}
{"id":"AJFS-A-2393-#as3","userId":3,"postDate":"2020-10-13","hidden":true}

場景一

搜尋發帖人userId為1或者帖子hidden為true,同時要求帖子的發帖日期絕對不為2020-12-16

GET /forum/post/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "should": [
            {
              "match": {
                "userId": 1
              }
            },
            {
              "match": {
                "hidden": true
              }  
            }
          ],
          "must_not": [
            {
              "match": {
                "postDate": "2020-12-16"
              }
            }
          ]
        }
      }
    }
  }
}

場景二

搜尋帖子userId為1,或者是帖子userId為3而且發帖日期為2020-10-13的帖子

GET /forum/post/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "should": [
            {
              "match": {
                "userId": 1
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "match": {
                      "userId": 3
                    }
                  },
                  {
                    "match": {
                      "postDate": "2020-10-13"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}

歡迎訪問我的個人部落格:小馬部落格

如果有疑問,歡迎諮詢公眾號《小馬JAVA》