简体   繁体   中英

Writing a Elasticsearch query to filter out a sentence

I'm writing a python program to query my elastic search index with a constraint that I have to retrieve all documents that contains three words (apple, mango, strawberry) while not containing a sentence ("this is not a fruit"). It seems like my query is okay except for the must_not part. It is retrieving correct documents that contain either of the three keywords, but seems like it doesn't filter out based on the sentence. The following is my query:

  res= es.search(index='fruit_box', body={

     'query': {

        "bool": {
            "must": [
                {
                   "query_string": {
                       "query": "(apple) OR (mango) OR (strawberry)"
                   }
                }
            ],
            "must_not": [
                {
                    "match": {
                        "text": "this is not a fruit"
                    }
                }
            ]
        }
    }
})

Am I missing something here? Thanks for any help in advance

your must_not clause is not in AND with the query_string one. For doing so, you have to move the must_not clause within the must array. Ie,

"query": {
  "bool": {
    "must": [
      {
        "query_string": {
          "query": "(apple) OR (mango) OR (strawberry)"
        }
      },
      {
        "bool": {
          "must_not": {
            "match": {
              "text": "this is not a fruit"
            }
          }
        }
      }
    ]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM