0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Index Document in Elasticsearch: Syntax and Example

To index a document in Elasticsearch, use the PUT or POST HTTP method with the target index and document ID in the URL, and include the document data as JSON in the request body. This stores the document so it can be searched later.
📐

Syntax

The basic syntax to index a document in Elasticsearch uses an HTTP PUT or POST request to the URL /{index}/_doc/{id}. Here:

  • {index} is the name of the index where you want to store the document.
  • _doc is the type placeholder (default in modern Elasticsearch versions).
  • {id} is the unique identifier for the document. If omitted with POST, Elasticsearch generates one.
  • The request body contains the document data in JSON format.
http
PUT /my-index/_doc/1
{
  "field1": "value1",
  "field2": "value2"
}
💻

Example

This example shows how to index a document with ID 1 into the index named products. The document contains a product name and price.

http
PUT /products/_doc/1
{
  "name": "Coffee Mug",
  "price": 12.99
}
Output
{ "_index": "products", "_id": "1", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 0, "_primary_term": 1 }
⚠️

Common Pitfalls

Common mistakes when indexing documents include:

  • Using POST without letting Elasticsearch generate an ID but not specifying one, which can cause duplicates.
  • Forgetting to specify the correct index name, leading to documents stored in unexpected places.
  • Sending malformed JSON in the request body, causing errors.
  • Not handling the response to check if the document was created or updated.
http
POST /products/_doc
{
  "name": "Tea Cup",
  "price": 8.99
}

# This lets Elasticsearch generate an ID automatically.

# Wrong: Missing JSON braces or syntax errors will cause failure.
POST /products/_doc
{
  "name": "Tea Cup",
  "price": 8.99
}
📊

Quick Reference

ActionHTTP MethodURL PatternDescription
Index document with IDPUT/{index}/_doc/{id}Stores or updates a document with the specified ID
Index document without IDPOST/{index}/_docStores a document and Elasticsearch generates an ID
Check responseN/AN/ALook for "result": "created" or "updated" in response

Key Takeaways

Use PUT with an ID or POST without an ID to index documents in Elasticsearch.
Always send document data as JSON in the request body.
Check the response to confirm if the document was created or updated.
Ensure the index name is correct to avoid storing documents in the wrong place.
Avoid JSON syntax errors to prevent request failures.