At times, we may have a set of IDs that we would like to get them from Elasticsearch. The IDs query, as the name suggests, fetches the documents given a set of document IDs. It’s a much simpler way to fetch the documents in one go. The following listing shows how to retrieve some documents using a list of document IDs.
GET movies/_search
{
"query": {
"ids": {
"values": [10,4,6,8]
}
}
}
This query returns four documents with the corresponding four IDs. Each document that gets indexed has a mandatory _id
field.
The metadata fields (like
_id
) can’t be part of the mapping schema. The _id field, along with other metadata fields like_source, _size, _routing
etc. are part of the metadata fields pack and hence are not allowed to be part of the index mapping exercise.
We can also use a terms query to fetch documents if we have a set of document IDs instead of an IDs query. The following listing shows how we can do this.
GET movies/_search
{
"query": {
"terms": {
"_id":[10,4,6,8]
}
}
}
Here, we use a terms query, setting the array of document identifiers on the _id
field as our search criteria.
These short articles are condensed excerpts taken from my book Elasticsearch in Action, Second Edition. The code is available in my GitHub repository.