Elasticsearch in Action: IDs queries

Madhusudhan Konda
2 min readOct 22, 2022
Excerpts taken from my upcoming book: Elasticsearch in Action

I will be presenting these short and condensed articles a mini-series on each of the topics in the next few months. The excerpts are taken from my book Elasticsearch in Action, Second Edition. The code is available in my GitHub repository. You can find executable Kibana scripts in the repository so you can run the commands in Kibana straight away. All code is tested against Elasticsearch 8.4+ version.

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.

Elasticsearch in Action

--

--

Madhusudhan Konda
Madhusudhan Konda

Written by Madhusudhan Konda

Madhusudhan Konda is a full-stack lead engineer, mentor, and conference speaker. He delivers live online training on Elasticsearch, Elastic Stack &Spring Cloud

No responses yet