0
0
Elasticsearchquery~5 mins

Why documents are the unit of data in Elasticsearch

Choose your learning style9 modes available
Introduction

Documents are the main way Elasticsearch stores and organizes data. They keep all related information together in one place, making it easy to search and manage.

When you want to store a complete record like a user profile or a product description.
When you need to search for information quickly across many pieces of data.
When you want to update or delete a single piece of data without affecting others.
When you want to group related information together for easy retrieval.
When you want to index data so Elasticsearch can find it fast.
Syntax
Elasticsearch
{
  "_index": "index_name",
  "_id": "document_id",
  "_source": {
    "field1": "value1",
    "field2": "value2",
    "field3": "value3"
  }
}

Each document is a JSON object with fields and values.

Documents live inside an index, which is like a folder for similar data.

Examples
This document stores a user's name, age, and city.
Elasticsearch
{
  "_index": "users",
  "_id": "1",
  "_source": {
    "name": "Alice",
    "age": 30,
    "city": "New York"
  }
}
This document stores details about a product.
Elasticsearch
{
  "_index": "products",
  "_id": "100",
  "_source": {
    "product_name": "Coffee Mug",
    "price": 12.99,
    "in_stock": true
  }
}
Sample Program

This example adds a document about a book to the 'library' index and then retrieves it.

Elasticsearch
POST /library/_doc/1
{
  "title": "The Great Gatsby",
  "author": "F. Scott Fitzgerald",
  "year": 1925
}

GET /library/_doc/1
OutputSuccess
Important Notes

Documents are stored as JSON, which is easy to read and write.

Each document has a unique ID within its index.

Using documents helps Elasticsearch search and analyze data quickly.

Summary

Documents hold all related data together in Elasticsearch.

They are stored in indexes and identified by unique IDs.

This structure makes searching and managing data simple and fast.