Elasticsearch Cheatsheet: Essential Commands & Tips

Elasticsearch commands for search, indexing & analytics

Page content

Elasticsearch is a powerful distributed search and analytics engine built on Apache Lucene. This comprehensive cheatsheet covers essential commands, best practices, and quick references for working with Elasticsearch clusters.

elasticsearch

Note: Most examples in this guide use cURL for HTTP requests. If you’re new to cURL or need a quick reference for advanced options, check out our cURL Cheatsheet for detailed command-line HTTP request techniques.

Cluster Management

Check Cluster Health

All commands in this section use cURL to interact with Elasticsearch’s REST API. You can customize these requests with additional headers, authentication, and other options as needed.

# Basic health check
curl -X GET "localhost:9200/_cluster/health?pretty"

# Detailed cluster health with shard information
curl -X GET "localhost:9200/_cluster/health?level=shards&pretty"

# Check node information
curl -X GET "localhost:9200/_cat/nodes?v"

# Check cluster settings
curl -X GET "localhost:9200/_cluster/settings?pretty"

Node Operations

# List all nodes
curl -X GET "localhost:9200/_cat/nodes?v&h=name,node.role,heap.percent,ram.percent,cpu,load_1m"

# Node stats
curl -X GET "localhost:9200/_nodes/stats?pretty"

# Hot threads (troubleshooting)
curl -X GET "localhost:9200/_nodes/hot_threads"

Index Management

Create and Delete Indices

# Create index
curl -X PUT "localhost:9200/my_index?pretty"

# Create index with settings
curl -X PUT "localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  }
}
'

# Delete index
curl -X DELETE "localhost:9200/my_index?pretty"

# List all indices
curl -X GET "localhost:9200/_cat/indices?v"

# Index statistics
curl -X GET "localhost:9200/my_index/_stats?pretty"

Index Mappings

# Define mapping
curl -X PUT "localhost:9200/products" -H 'Content-Type: application/json' -d'
{
  "mappings": {
    "properties": {
      "name": { "type": "text" },
      "price": { "type": "float" },
      "created_at": { "type": "date" },
      "tags": { "type": "keyword" },
      "description": { 
        "type": "text",
        "analyzer": "english"
      }
    }
  }
}
'

# Get mapping
curl -X GET "localhost:9200/products/_mapping?pretty"

# Update mapping (add field)
curl -X PUT "localhost:9200/products/_mapping" -H 'Content-Type: application/json' -d'
{
  "properties": {
    "category": { "type": "keyword" }
  }
}
'

Index Templates

# Create index template
curl -X PUT "localhost:9200/_index_template/logs_template" -H 'Content-Type: application/json' -d'
{
  "index_patterns": ["logs-*"],
  "template": {
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "properties": {
        "timestamp": { "type": "date" },
        "message": { "type": "text" },
        "level": { "type": "keyword" }
      }
    }
  }
}
'

# List templates
curl -X GET "localhost:9200/_index_template?pretty"

Document Operations (CRUD)

Create Documents

# Index document with auto-generated ID
curl -X POST "localhost:9200/products/_doc?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99,
  "tags": ["electronics", "computers"]
}
'

# Index document with specific ID
curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99
}
'

# Bulk indexing
curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d'
{ "index": { "_index": "products", "_id": "1" }}
{ "name": "Laptop", "price": 999.99 }
{ "index": { "_index": "products", "_id": "2" }}
{ "name": "Mouse", "price": 29.99 }
'

Read Documents

# Get document by ID
curl -X GET "localhost:9200/products/_doc/1?pretty"

# Get multiple documents
curl -X GET "localhost:9200/_mget?pretty" -H 'Content-Type: application/json' -d'
{
  "docs": [
    { "_index": "products", "_id": "1" },
    { "_index": "products", "_id": "2" }
  ]
}
'

# Check if document exists
curl -I "localhost:9200/products/_doc/1"

Update Documents

# Update document
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": {
    "price": 899.99
  }
}
'

# Update with script
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "script": {
    "source": "ctx._source.price *= params.discount",
    "params": {
      "discount": 0.9
    }
  }
}
'

# Upsert (update or insert)
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": {
    "price": 899.99
  },
  "doc_as_upsert": true
}
'

Delete Documents

# Delete by ID
curl -X DELETE "localhost:9200/products/_doc/1?pretty"

# Delete by query
curl -X POST "localhost:9200/products/_delete_by_query?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "name": "old"
    }
  }
}
'

Search Queries

# Match all
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match_all": {}
  }
}
'

# Match query
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "name": "laptop"
    }
  }
}
'

# Multi-match query
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "multi_match": {
      "query": "laptop gaming",
      "fields": ["name", "description"]
    }
  }
}
'

Term-Level Queries

# Term query (exact match)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "term": {
      "tags": "electronics"
    }
  }
}
'

# Terms query (multiple values)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "terms": {
      "tags": ["electronics", "computers"]
    }
  }
}
'

# Range query
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "range": {
      "price": {
        "gte": 100,
        "lte": 1000
      }
    }
  }
}
'

# Exists query
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "exists": {
      "field": "description"
    }
  }
}
'

Boolean Queries

# Bool query (must, should, must_not, filter)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "bool": {
      "must": [
        { "match": { "name": "laptop" }}
      ],
      "filter": [
        { "range": { "price": { "gte": 500 }}}
      ],
      "should": [
        { "term": { "tags": "gaming" }}
      ],
      "must_not": [
        { "term": { "tags": "refurbished" }}
      ]
    }
  }
}
'
# Wildcard query
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "wildcard": {
      "name": "lap*"
    }
  }
}
'

# Fuzzy query (typo tolerance)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "fuzzy": {
      "name": {
        "value": "laptpo",
        "fuzziness": "AUTO"
      }
    }
  }
}
'

# Prefix query
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "prefix": {
      "name": "lap"
    }
  }
}
'

Aggregations

Metric Aggregations

# Average, sum, min, max
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "avg_price": { "avg": { "field": "price" }},
    "max_price": { "max": { "field": "price" }},
    "min_price": { "min": { "field": "price" }},
    "total_sales": { "sum": { "field": "price" }}
  }
}
'

# Stats aggregation
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "price_stats": {
      "stats": { "field": "price" }
    }
  }
}
'

Bucket Aggregations

# Terms aggregation (group by)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "popular_tags": {
      "terms": {
        "field": "tags",
        "size": 10
      }
    }
  }
}
'

# Range aggregation
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 50 },
          { "from": 50, "to": 100 },
          { "from": 100 }
        ]
      }
    }
  }
}
'

# Date histogram
curl -X GET "localhost:9200/logs/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "logs_over_time": {
      "date_histogram": {
        "field": "timestamp",
        "calendar_interval": "day"
      }
    }
  }
}
'

Nested Aggregations

# Nested aggregations
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "categories": {
      "terms": { "field": "category" },
      "aggs": {
        "avg_price": {
          "avg": { "field": "price" }
        }
      }
    }
  }
}
'

Sorting and Pagination

# Sort by field
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": { "match_all": {} },
  "sort": [
    { "price": { "order": "desc" }},
    { "_score": { "order": "desc" }}
  ]
}
'

# Pagination with from/size
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "from": 0,
  "size": 10,
  "query": { "match_all": {} }
}
'

# Search after (for deep pagination)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 10,
  "query": { "match_all": {} },
  "sort": [{ "price": "asc" }, { "_id": "asc" }],
  "search_after": [100, "product_123"]
}
'

Field Selection and Highlighting

# Select specific fields
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": { "match_all": {} },
  "_source": ["name", "price"]
}
'

# Highlighting
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": { "description": "gaming laptop" }
  },
  "highlight": {
    "fields": {
      "description": {}
    }
  }
}
'

Index Aliases

# Create alias
curl -X POST "localhost:9200/_aliases?pretty" -H 'Content-Type: application/json' -d'
{
  "actions": [
    { "add": { "index": "products_v1", "alias": "products" }}
  ]
}
'

# Switch alias to new index (zero downtime)
curl -X POST "localhost:9200/_aliases?pretty" -H 'Content-Type: application/json' -d'
{
  "actions": [
    { "remove": { "index": "products_v1", "alias": "products" }},
    { "add": { "index": "products_v2", "alias": "products" }}
  ]
}
'

# List aliases
curl -X GET "localhost:9200/_cat/aliases?v"

Reindex

# Reindex from one index to another
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "old_products"
  },
  "dest": {
    "index": "new_products"
  }
}
'

# Reindex with query
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "products",
    "query": {
      "range": {
        "price": { "gte": 100 }
      }
    }
  },
  "dest": {
    "index": "expensive_products"
  }
}
'

Snapshots and Backups

# Register snapshot repository
curl -X PUT "localhost:9200/_snapshot/my_backup?pretty" -H 'Content-Type: application/json' -d'
{
  "type": "fs",
  "settings": {
    "location": "/mount/backups/my_backup"
  }
}
'

# Create snapshot
curl -X PUT "localhost:9200/_snapshot/my_backup/snapshot_1?wait_for_completion=true&pretty"

# Restore snapshot
curl -X POST "localhost:9200/_snapshot/my_backup/snapshot_1/_restore?pretty"

# List snapshots
curl -X GET "localhost:9200/_snapshot/my_backup/_all?pretty"

# Delete snapshot
curl -X DELETE "localhost:9200/_snapshot/my_backup/snapshot_1?pretty"

Performance Optimization

Index Settings

# Disable refresh during bulk indexing
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "-1"
  }
}
'

# Re-enable after bulk indexing
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "1s"
  }
}
'

# Force merge (optimize)
curl -X POST "localhost:9200/products/_forcemerge?max_num_segments=1&pretty"

Cache Clearing

# Clear all caches
curl -X POST "localhost:9200/_cache/clear?pretty"

# Clear specific cache
curl -X POST "localhost:9200/products/_cache/clear?query=true&pretty"

Monitoring and Troubleshooting

# Pending tasks
curl -X GET "localhost:9200/_cat/pending_tasks?v"

# Thread pool stats
curl -X GET "localhost:9200/_cat/thread_pool?v"

# Segment information
curl -X GET "localhost:9200/_cat/segments?v"

# Recovery information
curl -X GET "localhost:9200/_cat/recovery?v&h=index,stage,time"

# Tasks API
curl -X GET "localhost:9200/_tasks?detailed=true&pretty"

Python Client Examples

from elasticsearch import Elasticsearch

# Connect to Elasticsearch
es = Elasticsearch(['http://localhost:9200'])

# Index document
doc = {
    'name': 'Laptop',
    'price': 999.99,
    'tags': ['electronics']
}
es.index(index='products', id=1, document=doc)

# Search
resp = es.search(index='products', query={'match': {'name': 'laptop'}})
for hit in resp['hits']['hits']:
    print(hit['_source'])

# Bulk indexing
from elasticsearch.helpers import bulk

actions = [
    {
        '_index': 'products',
        '_id': i,
        '_source': {'name': f'Product {i}', 'price': i * 10}
    }
    for i in range(1000)
]
bulk(es, actions)

JavaScript/Node.js Client Examples

The Elasticsearch JavaScript client provides a type-safe way to interact with your cluster. For production applications, consider using TypeScript for better type safety and autocompletion. See our TypeScript Cheatsheet for best practices on type definitions and interfaces.

const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });

// Index document
async function indexDoc() {
  await client.index({
    index: 'products',
    id: 1,
    document: {
      name: 'Laptop',
      price: 999.99
    }
  });
}

// Search
async function search() {
  const result = await client.search({
    index: 'products',
    query: {
      match: { name: 'laptop' }
    }
  });
  console.log(result.hits.hits);
}

// Bulk indexing
async function bulkIndex() {
  const operations = [];
  for (let i = 0; i < 1000; i++) {
    operations.push({ index: { _index: 'products', _id: i } });
    operations.push({ name: `Product ${i}`, price: i * 10 });
  }
  await client.bulk({ operations });
}

TypeScript Example with Strong Typing

import { Client } from '@elastic/elasticsearch';

interface Product {
  name: string;
  price: number;
  tags?: string[];
  created_at?: Date;
}

const client = new Client({ node: 'http://localhost:9200' });

async function indexProduct(product: Product, id: number): Promise<void> {
  await client.index<Product>({
    index: 'products',
    id: id.toString(),
    document: product
  });
}

async function searchProducts(query: string): Promise<Product[]> {
  const result = await client.search<Product>({
    index: 'products',
    query: {
      match: { name: query }
    }
  });
  
  return result.hits.hits.map(hit => hit._source as Product);
}

Best Practices

Index Design

  • Keep shard size between 20-50GB for optimal performance
  • Use index lifecycle management (ILM) for time-series data
  • Design mappings carefully before indexing data
  • Use appropriate field types (keyword vs text, date formats)
  • Disable _source for large documents if not needed

Query Optimization

  • Use filters instead of queries when scoring isn’t needed
  • Prefer term-level queries for structured data
  • Use bool query to combine multiple conditions efficiently
  • Implement pagination with search_after for deep paging
  • Cache frequently used filters

Indexing Performance

  • Use bulk API for batch indexing (1000-5000 docs per request)
  • Disable refresh during bulk operations
  • Increase index.refresh_interval during heavy indexing
  • Use multiple threads/workers for parallel indexing
  • Consider using routing for better shard distribution

Cluster Management

  • Monitor cluster health regularly
  • Set up proper replica configuration
  • Use dedicated master nodes for large clusters
  • Implement proper backup strategy with snapshots
  • Monitor JVM heap usage (keep below 75%)

Security

  • Enable authentication and authorization (X-Pack Security)
  • Use HTTPS for production deployments (configure cURL with --cacert, --cert, and --key options for SSL/TLS)
  • Implement proper role-based access control
  • Regular security updates and patches
  • Encrypt data at rest and in transit

Common Use Cases

Elasticsearch excels at full-text search with features like:

  • Relevance scoring
  • Fuzzy matching
  • Phrase matching
  • Synonym handling
  • Multi-language support

Log Analytics (ELK Stack)

  • Collect logs with Logstash/Filebeat
  • Index and search logs in Elasticsearch
  • Visualize with Kibana dashboards
  • Set up alerts for anomalies
  • Product catalog search
  • Faceted navigation with aggregations
  • Auto-complete and suggestions
  • Personalized search results

Application Performance Monitoring

  • Index application metrics
  • Real-time monitoring dashboards
  • Anomaly detection
  • Performance trend analysis

Official Elasticsearch Resources