How to Get a Document in Elasticsearch: Syntax and Example
To get a document in Elasticsearch, use the
GET API with the URL format /{index}/_doc/{id}. This fetches the document by its unique id from the specified index.Syntax
The basic syntax to get a document in Elasticsearch is:
GET /{index}/_doc/{id}: Retrieves the document with the givenidfrom the specifiedindex.{index}: The name of the index where the document is stored.{id}: The unique identifier of the document.
This request returns the document if it exists, or a 404 error if not found.
http
GET /my_index/_doc/1Example
This example shows how to get a document with ID 1 from the index my_index using Elasticsearch's REST API.
http
GET /my_index/_doc/1 Response: { "_index": "my_index", "_type": "_doc", "_id": "1", "_version": 1, "found": true, "_source": { "title": "Learn Elasticsearch", "author": "Jane Doe", "year": 2024 } }
Output
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"title": "Learn Elasticsearch",
"author": "Jane Doe",
"year": 2024
}
}
Common Pitfalls
Common mistakes when getting documents in Elasticsearch include:
- Using the wrong
indexname, which causes a404error. - Requesting a document ID that does not exist, resulting in
found": falsein the response. - Confusing the
_searchAPI withGETby ID;_searchis for queries, not direct document retrieval.
Always verify the index and document ID before making the request.
http
Wrong: GET /wrong_index/_doc/1 Right: GET /my_index/_doc/1
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Get document by ID | GET /{index}/_doc/{id} | Fetches a document by its unique ID from the specified index. |
| Check if document exists | GET /{index}/_doc/{id} | Returns found: false if document is missing. |
| Wrong index error | GET /wrong_index/_doc/{id} | Returns 404 if index does not exist. |
Key Takeaways
Use GET /{index}/_doc/{id} to retrieve a document by its ID in Elasticsearch.
Ensure the index name and document ID are correct to avoid 404 errors.
The response includes a 'found' field indicating if the document exists.
Do not confuse document retrieval with search queries using _search API.