Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
Michaël Perrin Avatar asked Nov 26 '14 14:11

Michaël Perrin


People also ask

What is _source in Elasticsearch query?

The _source field contains the original JSON document body that was passed at index time. The _source field itself is not indexed (and thus is not searchable), but it is stored so that it can be returned when executing fetch requests, like get or search.

Does Elasticsearch preserve order?

According to documentation: When you get a document back from Elasticsearch, any arrays will be in the same order as when you indexed the document.

How do I get all Elasticsearch index data?

You can use cURL in a UNIX terminal or Windows command prompt, the Kibana Console UI, or any one of the various low-level clients available to make an API call to get all of the documents in an Elasticsearch index. All of these methods use a variation of the GET request to search the index.

What is Terms query in Elasticsearch?

You can use the term query to find documents based on a precise value such as a price, a product ID, or a username. Avoid using the term query for text fields. By default, Elasticsearch changes the values of text fields as part of analysis. This can make finding exact matches for text field values difficult.


1 Answers

At the end the answer was pretty easy: you have to use the _source query option insteand 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" }
like image 142
Michaël Perrin Avatar answered Oct 15 '22 18:10

Michaël Perrin