首页 > 解决方案 > 使用弹性搜索查询过滤和匹配

问题描述

我在下面的弹性搜索查询中应用辅助过滤器时遇到问题。只有第一个过滤器匹配。我希望两个过滤器都应用于查询。

  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "filter": {
              "range": {
                "@timestamp": {
                  "gte": "2019-03-12",
                  "lte": "2019-03-13"
                }
              }
            }
          }
        },
        {
          "bool": {
            "filter": {
              "bool": {
                "must": {
                  "match": {
                    "msg_text": "foo AND bar"
                  }
                }
              }
            }
          }
        }
      ]
    }
  }

标签: elasticsearch

解决方案


Well I've mentioned two solutions, first one makes use of Match Query while the second one makes use of Query String.

Also I'm assuming msg_text field is of type text.

Difference is that, query_string uses a parser, that would parse the text you mention based on the operators like AND, OR.

While match query would read the text, analyse the text and based on it constructs a bool query. In the sense you don't need to mention operators and it won't work

You can read more about them in the links I've mentioned.

1. Using Match Query

POST <your_index_name>/_search
{  
   "query":{  
      "bool":{  
         "filter":{  
            "bool":{  
               "must":[  
                  {  
                     "range":{  
                        "@timestamp":{  
                           "gte":"2019-03-12",
                           "lte":"2019-03-13"
                        }
                     }
                  },
                  {  
                     "match":{  
                        "msg_text":"foo bar"         
                     }
                  }
               ]
            }
         }
      }
   }
}

2. Using Query String

POST <your_index_name>/_search
{  
   "query":{  
      "bool":{  
         "filter":{  
            "bool":{  
               "must":[  
                  {  
                     "range":{  
                        "@timestamp":{  
                           "gte":"2019-03-12",
                           "lte":"2019-03-13"
                        }
                     }
                  },
                  {  
                     "query_string":{  
                        "fields": ["msg_text"],    <----- You can add more fields here using comma as delimiter
                        "query":"foo AND bar"
                     }
                  }
               ]
            }
         }
      }
   }
}

Technically nothing is wrong with your solution, in the sense, it would work, but I hope my answers clear, simplifies the query and helps you understand what you are trying to do.

Let me know if it helps!


推荐阅读