1

Elasticsearch's search API supports a "fields" parameter to limit the fields returned from the hits. It supports dot notation for sub-properties of a document as well. For example, a query

{
    "fields" : ["user.lastname"],
    "query" : {
        "term" : { "_id" : 1 }
    }
}

will return hits as:

{
   "hits": [
        {"_id": 1,
         "user.lastname": "Smith"}
  ]
}

I am wondering if there is an option to make it return as this instead:

{
   "hits": [
        {"_id": 1,
         "user": {"lastname": "Smith"}}
  ]
}

The benefit of the second one is maintaining the same structure as the full document, as that the following data access logic is consistent.

nelsonvarela
  • 2,310
  • 7
  • 27
  • 43

1 Answers1

0

Yes, if you use source filtering instead (i.e. _source instead of fields), you'll get the expected results, i.e.

POST index/_search
{
    "_source" : ["user.lastname"],
    "query" : {
        "term" : { "_id" : 1 }
    }
}

Results:

{
   "hits": [
      {
         "_id": 1,
         "_source": {
             "user": {"lastname": "Smith"}
         }
      }
  ]
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • Isn't there any way to have the same structure returned in the fields object? I am using the fields object to render data in a template in Django but in Django variables and attributes may not begin with underscores. So I can not use _source directly in the template – nelsonvarela Dec 22 '15 at 10:39
  • You could try to use a [custom template filter](http://stackoverflow.com/a/13694031/4604579)? – Val Dec 22 '15 at 10:46