Using filter beside query_string in Elastic Search

12,422

Solution 1

Yep, the syntax of the filtered query is a bit cumbersome. AFAIK it should look like that:

{
   "query":{
      "filtered":{
         "query":{
            "query_string":{
               "query":"Declared"
            }
         },
         "filter":{
            "term":{
               "language_id":10
            }
         }
      }
   }
}

Solution 2

In version 5.2, filtered query is replaced by the bool query, and returns error on my Elastic 5.2 instance. See here.

The new syntax is:

{
   "query":{
      "bool":{
         "must":{
            "query_string":{
               "query":"Declared"
            }
         },
         "filter":{
            "term":{
               "language_id":10
            }
         }
      }
   }
}

Solution 3

Sorry Ashalynd but the filter is not placed a the right place in your answer.

This is working better:

{
   "query":{
      "filtered":{
         "query":{
            "query_string":{
               "query":"Declared"
            }
         },
         "filter":{
            "term":{
               "language_id":10
            }
         }
      }
   }
}
Share:
12,422
ehsan shirzadi
Author by

ehsan shirzadi

I'm Ehsan. Currently I'm a backend developer and also DevOps engineer of an international company. My personal interests are: Development of big project in scrum framework Taking advantage of new technologies Distributed systems Big data management Real time processing If you want to develop your projects, you can count on me, please contact me: [email protected] thank you.

Updated on June 04, 2022

Comments

  • ehsan shirzadi
    ehsan shirzadi almost 2 years

    How to full text search and have filter? I want to search for a text among documents with language_id=10. I've tried it this way:

    {
      "query": {
        "query_string": {
          "query": "Declared"
        },
        {
          "filtered": {
            "filter": {
              "term": {
                "language_id": 10
              }
            }
          }
        }
      }
    }
    

    but seems like it's not correct. How to correct it?

  • minocha
    minocha about 8 years
    it is this which works and not the one mentioned by @Ashalynd .. Was a big help thanks!
  • minocha
    minocha about 8 years
    I tried your format but it doesn't work, the filters are working better in the format of @Kévin 's answer. Please have a look
  • Ashalynd
    Ashalynd about 8 years
    Ah that was a typo, fixed
  • Ricardo
    Ricardo almost 5 years
    Validated on ES 6.7.2