0
0
Elasticsearchquery~5 mins

Indexing a document (POST/PUT) in Elasticsearch

Choose your learning style9 modes available
Introduction

Indexing a document means saving data into Elasticsearch so you can search it later. It helps organize and store information quickly.

When you want to add a new record to your search database.
When you need to update an existing record with new information.
When you want to store logs or events for quick searching.
When you want to save user profiles or product details for search.
When you want to keep your data ready for fast retrieval.
Syntax
Elasticsearch
POST /index_name/_doc
{
  "field1": "value1",
  "field2": "value2"
}

PUT /index_name/_doc/document_id
{
  "field1": "new_value1",
  "field2": "new_value2"
}

Use POST without an ID to let Elasticsearch create a unique ID automatically.

Use PUT with a specific ID to create or replace a document with that ID.

Examples
Adds a new product document with an auto-generated ID.
Elasticsearch
POST /products/_doc
{
  "name": "Coffee Mug",
  "price": 12.99
}
Creates or updates the product with ID 123.
Elasticsearch
PUT /products/_doc/123
{
  "name": "Tea Cup",
  "price": 9.99
}
Indexes a new log event with an automatic ID.
Elasticsearch
POST /logs/_doc
{
  "event": "user_login",
  "user": "alice"
}
Sample Program

This example adds a book document to the 'library' index with details about the title, author, and year.

Elasticsearch
POST /library/_doc
{
  "title": "The Little Prince",
  "author": "Antoine de Saint-Exupéry",
  "year": 1943
}
OutputSuccess
Important Notes

Elasticsearch automatically creates the index if it does not exist when you index a document.

Using PUT with an existing ID replaces the whole document.

Always check the response to confirm if the document was created or updated.

Summary

Indexing stores data in Elasticsearch for searching.

Use POST to add with auto ID, PUT to add or replace with a specific ID.

Check the response to know if the operation succeeded.