0
0
ElasticsearchHow-ToBeginner · 3 min read

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 given id from the specified index.
  • {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/1
💻

Example

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 index name, which causes a 404 error.
  • Requesting a document ID that does not exist, resulting in found": false in the response.
  • Confusing the _search API with GET by ID; _search is 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

ActionSyntaxDescription
Get document by IDGET /{index}/_doc/{id}Fetches a document by its unique ID from the specified index.
Check if document existsGET /{index}/_doc/{id}Returns found: false if document is missing.
Wrong index errorGET /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.