10
{
    class: 1,
    users: [{
        name: 'abc',
        surname: 'def'
    }, {
        name: 'xyz',
        surname: 'wef'
    }, {
        name: 'abc',
        surname: 'pqr'
    }]
}

I have a document structure like above object and I want to return only users who have name 'abc' but problem is it matches name 'abc' but returns all array. I want only matched users .

Mapping -

{
        "class":"string",
        "users" : {
            "type" : "nested",
            "properties": {
                "name" : {"type": "string" },
                "surname"  : {"type": "string" }
            }
        }
    }
1
  • Can you show your query? and possibly also your mapping? Commented Jul 30, 2015 at 9:35

1 Answer 1

17

Then if you have your users field mapped as nested type, it's a good start!

Using nested inner_hits, you can retrieve only the matching user names with a query like this one:

{
  "_source": false,
  "query": {
    "nested": {
      "path": "users",
      "inner_hits": {        <---- this is where the magic happens
        "_source": [
          "name"
        ]
      },
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "users.name": "abc"
              }
            }
          ]
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

can we do "_source": false for specific _type ?
You can definitely narrow your search query to a specify type by specifying the type directly in the URL /my_index/my_type/_search if that's what you mean.
Can we get all normal fields with only matching nested fields ? like { class: 1, users: [{ name: 'abc', surname: 'def' }] }
@JayShah If you set _source: true it should get you what you want
Yes, but if I set _source: true, It gives me all nested objects. I need only matching nested objects. like { class: 1, users: [{ name: 'abc', surname: 'def' }] } Is that possible ?
|

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.