0

Given doc: books

[
 {
  name: "book a",
  authors: 
  [
   {
    name: "John",
   }
   {
    name: "Paul"
   }
  ]
 },
 {
  name: "book b",
  authors: 
  [
   {
    name: "Paul"
   }
  ]
 }
]

Goal: Return the book which match name = book a AND match one of the author name with authors.name = John.

What I tried:

      "must": [
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "must": [
                    {
                      "term": {
                        "name": {
                          "value": "book a"
                        }
                      }
                    },
                    {
                      "bool": {
                        "should": [
                          {
                            "term": {
                              "authors.name": {
                                "value": "John"
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]

mapping name: text authors: dynamic

5
  • book a and book b is part of single elasticsearch document or seperate document in elasticsearch index. Commented Oct 19, 2022 at 12:50
  • seperate document @SagarPatel Commented Oct 19, 2022 at 13:01
  • Can you please put index mapping for your book index. Commented Oct 19, 2022 at 13:18
  • @SagarPatel ty for comment, updated with mappings. Commented Oct 19, 2022 at 13:28
  • @Shawan I have updated my answer based on mapping you have provided. Please check it. Commented Oct 19, 2022 at 13:30

1 Answer 1

1

You can use below query:

Please note that, if you are using dynemic mapping of elasticsearch then used name.keyword and authors.name.keyword. otherwise use name and authors.name if you have specified your custom mapping.

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "book a"
          }
        },
        {
          "term": {
            "authors.name.keyword": {
              "value": "John"
            }
          }
        }
      ]
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wondering why we need the .keyword to make it works? Also, both match and term are in must not should?
You need .keyword because term query work with keyword type of field only and it will look for exact match. Also, it is required in must because you have mentioned to match as AND. If you specify as should then atleast on condition match then result will be return.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.