Querying Nested Object returns all objects

I was testing the example given on elasticsearch nested object documentation. In that example, why it returns both records even though i'm querying for values that only matches with 1 record. Please see below: -

Mapping: -

PUT my_index
{
  "mappings": {
    "_doc":{
      "properties": {
        "user": {
          "type": "nested" 
        }
      }
    }
  }
}

PUT my_index/_doc/1
{
 "group" : "fans",
  "user" : [
    {
      "first" : "John",
      "last" :  "Smith"
    },
    {
      "first" : "Alice",
      "last" :  "White"
    }
  ]
}

Query: -

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "user",
      "query": {
        "bool": {
          "must": [
            { "match": { "user.first": "John" }},
            { "match": { "user.last":  "Smith" }}
          ]
        }
      }
    }
  }
}

Actual Output: -

  "hits": {
    "total": 1,
    "max_score": 1.3862944,
    "hits": [
      {
        "_index": "my_index",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.3862944,
        "_source": {
          "group": "fans",
          "user": [
            {
              "first": "John",
              "last": "Smith"
            },
            {
              "first": "Alice",
              "last": "White"
            }
          ]
        }
      }
    ]
  }
}

Desired Output:-

  "hits": {
    "total": 1,
    "max_score": 1.3862944,
    "hits": [
      {
        "_index": "my_index",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.3862944,
        "_source": {
          "group": "fans",
          "user": [
            {
              "first": "John",
              "last": "Smith"
            }
          ]
        }
      }
    ]
  }
}

If something is wrong with my query, then what would be the correct query to get the desired output shown above?

Thank You,
Bhaumik

Hey,

first, please take the time to properly format your code, as you can use markdown. This makes your post a million times more readable and thus also more likely to get an answer. Thanks!

Regarding your problem, you should take a look at the inner_hits functionality

--Alex

1 Like

Thank you Alexandar and sorry about the code format, I have updated it.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.