Elasticsearch Common Commands: Index, Document, Query & Cluster Reference
This article provides a comprehensive reference of Elasticsearch 7.x+ RESTful API commands covering index management, document CRUD, query DSL (match, term, bool, aggregations), SQL access, cluster health, index aliases, reindexing, and _cat APIs with practical examples.
Elasticsearch provides rich RESTful APIs for managing indices, documents, and clusters. This reference covers common commands for Elasticsearch 7.x+ (with minor adjustments in 8.x).
Index Management
Create Index
PUT /products
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"name": { "type": "text" },
"price": { "type": "float" },
"create_time": { "type": "date" }
}
}
}Primary shards cannot be changed after creation; replicas can be adjusted dynamically.
View Index Information
GET /products
GET /products,users
GET /prod*
GET /_cat/indices?vModify Index Settings (Dynamic Only)
PUT /products/_settings
{
"number_of_replicas": 2
}Delete Index
DELETE /products
DELETE /products,users
DELETE /prod* # Avoid wildcard deletion in productionDocument Operations
Add Document
PUT /products/_doc/1
{
"name": "Elasticsearch实战",
"price": 89.0,
"create_time": "2023-01-01T12:00:00"
}
POST /products/_doc
{
"name": "Kibana指南",
"price": 69.0,
"create_time": "2023-01-02T10:30:00"
}Query Document
GET /products/_doc/1
GET /products/_search
GET /products/_search
{
"query": {
"range": {
"price": { "gt": 50 }
}
}
}Update Document
PUT /products/_doc/1
{
"name": "Elasticsearch实战(第2版)",
"price": 99.0,
"create_time": "2023-01-01T12:00:00"
}
POST /products/_update/1
{
"doc": {
"price": 89.0
}
}Full replacement requires the complete document; partial update uses _update with doc.
Delete Document
DELETE /products/_doc/1Query and Search
Queries are divided into Leaf Queries (direct field operations like match, term, range) and Compound Queries (combining leaf queries, e.g., bool, should, filter).
Full-Text Search (match family)
GET /products/_search
{
"query": {
"match": {
"name": "elasticsearch 实战"
}
}
}
GET /products/_search
{
"query": {
"match_phrase": {
"name": {
"query": "elasticsearch 实战",
"slop": 1
}
}
}
}
GET /products/_search
{
"query": {
"multi_match": {
"query": "实战",
"fields": ["name", "description^2"]
}
}
} match_phrasewith slop allows flexible phrase matching; multi_match supports field boosting with ^.
Exact Match and Filter (term family)
GET /products/_search
{
"query": {
"term": {
"category.keyword": "技术书籍"
}
}
}
GET /products/_search
{
"query": {
"terms": {
"price": [59, 69, 89]
}
}
}
GET /products/_search
{
"query": {
"range": {
"price": { "gte": 50, "lte": 100 },
"create_time": { "gte": "2023-01-01", "lte": "now" }
}
}
}Use .keyword for exact matching on text fields. range supports gte, lte, gt, lt and date math like now.
Compound Query (bool Logic)
GET /products/_search
{
"query": {
"bool": {
"must": [
{ "match": { "name": "elasticsearch" } },
{ "range": { "price": { "lt": 100 } } }
],
"should": [
{ "term": { "category.keyword": "技术书籍" } },
{ "term": { "tags": "编程" } }
],
"must_not": [
{ "term": { "status": "下架" } }
],
"filter": [
{ "range": { "create_time": { "gte": "2023-01-01" } } }
]
}
}
}Note: filter does not affect relevance scoring and results are cacheable, making it ideal for high-frequency filters (status, time ranges). must contributes to scoring.
Relevance Scoring and Boosting
Elasticsearch uses BM25 algorithm for _score. Boost weights in should clauses:
GET /products/_search
{
"query": {
"bool": {
"should": [
{ "match": { "name": { "query": "elasticsearch", "boost": 3 } } },
{ "match": { "description": { "query": "elasticsearch", "boost": 1 } } }
]
}
}
}Basic Aggregations
GET /products/_search
{
"size": 0,
"aggs": {
"category_count": {
"terms": { "field": "category.keyword", "size": 10 }
},
"avg_price": {
"avg": { "field": "price" }
}
}
}Nested Aggregations
GET /products/_search
{
"size": 0,
"aggs": {
"by_category": {
"terms": { "field": "category.keyword" },
"aggs": {
"avg_price": { "avg": { "field": "price" } },
"by_month": {
"date_histogram": {
"field": "create_time",
"calendar_interval": "month"
}
}
}
}
}
}Post Filter (Query Then Filter)
GET /products/_search
{
"query": { "match_all": {} },
"post_filter": {
"range": { "price": { "lt": 50 } }
},
"aggs": { "avg_price": { "avg": { "field": "price" } } }
} post_filterfilters returned documents without affecting aggregations, which run on the full dataset.
Complex Sorting
GET /products/_search
{
"query": { "match": { "name": "elasticsearch" } },
"sort": [
{ "price": { "order": "asc" } },
{ "_score": { "order": "desc" } }
]
}Script Queries
GET /products/_search
{
"query": {
"script": {
"script": {
"source": "doc['price'].value * doc['discount'].value < 100"
}
}
}
}SQL Syntax Queries
POST /_sql?format=txt
{
"query": "SELECT 字段名 FROM 索引名 WHERE 条件 LIMIT N"
}
POST /_sql?format=txt
{
"query": """
SELECT * FROM "products_*" limit 1
"""
} format=txtreturns plain text table; other formats: json (default), csv, yaml.
Request body query contains SQL statement supporting standard syntax: SELECT, WHERE, GROUP BY, ORDER BY, etc.
Supported SQL Features
Basic queries: SELECT (wildcard or specific fields), WHERE (conditions: =, >, LIKE).
Aggregations: GROUP BY, COUNT(), AVG(), SUM().
Sorting and pagination: ORDER BY, LIMIT, OFFSET.
SQL Considerations
Index names must follow SQL table naming rules; use backticks for special characters: SELECT * FROM `my-index`.
Field type sensitivity: date fields require DATE_FORMAT conversion, e.g., DATE_FORMAT(create_time, '%Y-%m-%d').
Performance: complex SQL may translate to inefficient Query DSL; prefer native DSL for high-frequency queries.
Permissions: ensure user has read privilege on target indices.
Cluster and Node Management
Cluster Health
GET /_cluster/health
# green: all primary and replica shards active
# yellow: primary shards active, replicas unassigned
# red: primary shards missingNode Information
GET /_cat/nodes?v
GET /_nodesShard Allocation
GET /_cat/shards?vIndex Aliases and Reindexing
Manage Aliases
POST /_aliases
{
"actions": [
{ "add": { "index": "products", "alias": "prod" } }
]
}
POST /_aliases
{
"actions": [
{ "remove": { "index": "products", "alias": "prod" } }
]
}Reindex
POST /_reindex
{
"source": { "index": "old_index" },
"dest": { "index": "new_index" }
}_cat API Tools
Compact tabular output for quick inspection:
GET /_cat/indices?v
GET /_cat/shards?v
GET /_cat/nodes?v
GET /_cat/health?v
GET /_cat/aliases?vImportant Notes
Production deletions (indices/documents) require caution; backup first.
Complex queries and bulk operations ( _bulk) should run during low-traffic periods.
Index names must be lowercase and cannot contain special characters: \ / * ? " < > |.
These commands cover 80% of daily development and operations scenarios. For advanced features (script updates, geo queries), consult the official documentation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Lakehouse Research Base
Focused on technical sharing in the data field, covering a tech stack that includes Hadoop, Spark, Flink, Kafka, Fluss, Paimon, Iceberg, StarRocks, ClickHouse, ES, Milvus, and more. Welcome to follow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
