0
0
Elasticsearchquery~5 mins

Retrieving a document by ID in Elasticsearch

Choose your learning style9 modes available
Introduction

We use document ID to quickly find one exact item in Elasticsearch. It is like looking up a book by its unique code in a library.

You want to get details of a specific user by their unique ID.
You need to fetch a product's information using its product ID.
You want to check if a particular document exists in your index.
You want to update or delete a document and need to retrieve it first.
You want to display a single record on a webpage by its ID.
Syntax
Elasticsearch
GET /index_name/_doc/document_id

Replace index_name with your index's name.

Replace document_id with the ID of the document you want to retrieve.

Examples
Retrieve the document with ID '123' from the 'users' index.
Elasticsearch
GET /users/_doc/123
Retrieve the document with ID 'abc-456' from the 'products' index.
Elasticsearch
GET /products/_doc/abc-456
If the document with ID '999' is not found in 'orders', the response will show it was not found.
Elasticsearch
GET /orders/_doc/999

# What if the document does not exist?
# Elasticsearch returns a response with "found": false.
Sample Program

This example first adds a document with ID '1' to the 'library' index. Then it retrieves the document with ID '1'. Finally, it tries to get a document with ID '2' which does not exist.

Elasticsearch
POST /library/_doc/1
{
  "title": "Learn Elasticsearch",
  "author": "Jane Doe",
  "year": 2024
}

GET /library/_doc/1

GET /library/_doc/2
OutputSuccess
Important Notes

Time complexity is very fast because Elasticsearch uses the document ID as a direct pointer.

Space complexity is minimal since no extra data structures are needed for retrieval.

A common mistake is using the wrong index name or ID, which causes the document not to be found.

Use this method when you know the exact ID. For searching by content, use search queries instead.

Summary

Retrieving by ID is the fastest way to get one exact document.

You must know the index and the document ID.

If the document is missing, Elasticsearch tells you with 'found': false.