How to Use IDs Query in Elasticsearch for Fast Document Lookup
Use the
ids query in Elasticsearch to quickly retrieve documents by specifying their unique IDs in the values array. This query is efficient for fetching exact documents without searching through fields.Syntax
The ids query requires specifying the values array containing the document IDs you want to retrieve. Optionally, you can specify the type if your index has multiple types (deprecated in newer versions).
- values: Array of document IDs to fetch.
- type: (Optional) Document type, mostly unused in modern Elasticsearch versions.
json
{
"query": {
"ids": {
"values": ["1", "2", "3"]
}
}
}Example
This example shows how to use the ids query to fetch documents with IDs "1", "2", and "3" from an Elasticsearch index.
json
{
"query": {
"ids": {
"values": ["1", "2", "3"]
}
}
}Output
{
"hits": {
"total": 3,
"hits": [
{"_id": "1", "_source": {"field": "value1"}},
{"_id": "2", "_source": {"field": "value2"}},
{"_id": "3", "_source": {"field": "value3"}}
]
}
}
Common Pitfalls
Common mistakes when using the ids query include:
- Using numeric IDs without quotes, which can cause errors because IDs are strings.
- Specifying the
typefield in newer Elasticsearch versions where types are deprecated. - Expecting the
idsquery to search fields other than the document ID.
Always ensure IDs are strings and avoid using type unless your cluster supports it.
json
{
"query": {
"ids": {
"values": [1, 2, 3]
}
}
}
// Correct usage:
{
"query": {
"ids": {
"values": ["1", "2", "3"]
}
}
}Quick Reference
| Parameter | Description | Required |
|---|---|---|
| values | Array of document IDs to retrieve | Yes |
| type | Document type (deprecated in newer versions) | No |
Key Takeaways
The ids query fetches documents by their unique IDs quickly and efficiently.
Always provide document IDs as strings inside the values array.
Avoid using the type parameter in modern Elasticsearch versions.
The ids query only matches document IDs, not other fields.
Use ids query for exact document lookups, not for full-text search.