0
0
ElasticsearchHow-ToBeginner · 4 min read

How to Create an Index in Elasticsearch Quickly and Easily

To create an index in Elasticsearch, use the PUT HTTP method with the index name in the URL, like PUT /my-index. You can optionally include settings and mappings in the request body to customize the index.
📐

Syntax

Creating an index in Elasticsearch uses the PUT method with the index name in the URL. You can add optional settings to configure shards and replicas, and mappings to define the structure of your data.

  • PUT /index-name: Creates the index with the given name.
  • settings: Customize index behavior like number of shards.
  • mappings: Define fields and their data types.
json
PUT /my-index
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "field1": { "type": "text" },
      "field2": { "type": "keyword" }
    }
  }
}
💻

Example

This example creates an index named products with 1 shard and 1 replica. It defines two fields: name as text and category as keyword for exact matches.

json
PUT /products
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "name": { "type": "text" },
      "category": { "type": "keyword" }
    }
  }
}
Output
{ "acknowledged": true, "shards_acknowledged": true, "index": "products" }
⚠️

Common Pitfalls

Common mistakes when creating an index include:

  • Using POST instead of PUT for index creation.
  • Not specifying mappings, which can lead to incorrect data types.
  • Setting too many shards for small data, which wastes resources.
  • Trying to create an index that already exists without deleting it first.

Always check if the index exists before creating it to avoid errors.

json
POST /my-index
{
  "settings": {
    "number_of_shards": 1
  }
}

# Correct way:
PUT /my-index
{
  "settings": {
    "number_of_shards": 1
  }
}
📊

Quick Reference

ActionSyntaxDescription
Create indexPUT /index-nameCreates a new index with the given name
Add settings"settings": {...}Configure shards, replicas, and other options
Define mappings"mappings": {...}Set field types and structure
Check index existsHEAD /index-nameCheck if an index already exists
Delete indexDELETE /index-nameRemove an existing index

Key Takeaways

Use the PUT method with the index name to create an index in Elasticsearch.
Include settings and mappings in the request body to customize your index.
Avoid common mistakes like using POST or missing mappings.
Check if the index exists before creating to prevent errors.
Keep shard count appropriate to your data size for better performance.