How to get documents that contain certain word in some fields with filtered query?

Viewed 56

I want to find all books with "Agriculture" category. the books should contain word "paddy" in the title OR abstract field. Here is my query :

GET /books/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "abstract": "paddy"
          }
        },
        {
          "match": {
            "title": "paddy"
          }
        }
      ],
      "filter": {
        "term": {
          "category": "Agriculture"
        }
      }
    }
  }
}

those query return all books with "Agriculture" category, even it's contain word "paddy" or not. What did I do wrong?

1 Answers

Let me first explain to you how, Your query was fetching all the records, even it contains word "paddy" or not. This is b/c you are using the should clause which simply means that The clause (query) should appear in the matching document. but it means it is not forcing that it must appear, hence it's fetching all the documents in your index and then just filtering it on basis of category.

What you need is an upper level must clause, which means it must appear but then I used nested should as it can be either in title or abstract field, but at least one of these fields must contain the value, so that upper level must clause returns true.

The right query is below, which I tried locally and working fine, according to your use case:

{
    "query": {
        "bool": {
            "must": {
                "bool": {
                    "should": [
                        {
                            "match": {
                                "abstract": "paddy"
                            }
                        },
                        {
                            "match": {
                                "title": "paddy"
                            }
                        }
                    ]
                }
            },
            "filter": {
                "term": {
                    "category": "agriculture"
                }
            }
        }
    }
}

Let me know if it's clear to you and solves your issue.

Related