3

I have a document with nested objects, something like this:

{
    "title" : "Title 1",
    "books": [{
        "book_title": "b title 1",
        "year": 2014
    }, {
        "book_title": "b title 2",
        "year": 2015
    }]
}

Now I need to filter the books on by title (not book_title) and year (let's say 2014). The output I need will be:

{
    "title" : "Title 1",
    "books": [{
        "book_title": "b title 1",
        "year": 2014
    }]
}

When I use a nested filter I get all the nested objects even if they don't match. How can I fetch only the matched nested objects?

1 Answer 1

6

You need to use the nested inner_hits feature like below.

{
  "_source": [
    "title"
  ],
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "title 1"
          }
        },
        {
          "nested": {
            "path": "books",
            "query": {
              "term": {
                "books.year": 2014
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  }
}

In the output you'll get exactly what you expect, namely the title field and the matching book from the nested books array.

Sign up to request clarification or add additional context in comments.

Comments

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.