Search code examples
elasticsearch

Is there any way not to return arrays when specifying return fields in an Elasticsearch query?


If I have a documents like this :

[
    {
        "model": "iPhone",
        "brand": "Apple"
    },
    {
        "model": "Nexus 5",
        "brand": "Google"
    }
]

And that I make a query which only returns the model field in a query, like this:

{
    "fields": ["model"],
    "query": {
        "term": {
            "brand": "apple"
        }
    }
}

Then each document field is returned within an array like this:

{ "model": ["iPhone"] }

instead of

{ "model": "iPhone" }

How can I avoid that and get the fields in the same format as when the fields query option is not defined?


Solution

  • At the end the answer was pretty easy: you have to use the _source query option instead of fields.

    Example:

    {
        "_source": ["model"],
        "query": {
            "term": {
                "brand": "apple"
            }
        }
    }
    

    This way I get documents in the following format, like in the original one (without the _source option):

    { "model": "iPhone" }