This lab creates an Elasticsearch index with a set number of primary shards and replicas, then runs the queries you'll use most often against it. The example above sets number_of_shards and number_of_replicas when the index is created. Below you'll find a corrected command that works on current Elasticsearch versions, ways to check where shards ended up, sample data, and common query patterns such as match, term, range, bool and aggregations.
What the example above does
The example above sends a PUT request to create an index named example. It sets two index settings: number_of_shards: 2 splits the data into two primary shards, and number_of_replicas: 1 keeps one copy of each primary. That makes four shards in total: two primaries and two replicas. Each shard is a separate Lucene index, and Elasticsearch places the shards on nodes across the cluster.
Elasticsearch never puts a replica on the same node as its primary. On a single-node lab cluster, the two replica shards stay unassigned and the index health is yellow. This is expected behaviour, not an error.
Note: The post title mentions queries, but the original example only creates the index. The query section further down covers the query part of the lab.
Corrected index creation command
Since Elasticsearch 6.0, any request with a JSON body must include a Content-Type: application/json header. If you leave it out, as the example above does, the request fails with HTTP 406. Use -X PUT with the URL in quotes:
curl -X PUT "http://localhost:9200/example" \
-H 'Content-Type: application/json' \
-d '{
"settings": {
"index": {
"number_of_shards": 2,
"number_of_replicas": 1
}
}
}'Code language: PHP (php)
Expected response:
{"acknowledged":true,"shards_acknowledged":true,"index":"example"}Code language: JSON / JSON with Comments (json)
Elasticsearch 8.x turns on security by default, so plain HTTP without credentials won't connect. Use HTTPS, the CA certificate created on first start (for example config/certs/http_ca.crt in an archive install), and the elastic user:
export ES_URL="https://localhost:9200"
export ES_AUTH="elastic:$ELASTIC_PASSWORD"
curl --cacert config/certs/http_ca.crt -u "$ES_AUTH" \
-X PUT "$ES_URL/example" \
-H 'Content-Type: application/json' \
-d '{"settings":{"index":{"number_of_shards":2,"number_of_replicas":1}}}'Code language: JavaScript (javascript)
The rest of this lab uses http://localhost:9200 to keep the commands short. On a secured cluster, add the same --cacert and -u options. In Kibana Dev Tools you can drop the curl wrapper and write PUT /example followed by the JSON body.
Verify settings and shard allocation
# Show the index settings
curl "http://localhost:9200/example/_settings?pretty"
# Show every shard, whether it is a primary (p) or replica (r), and its state
curl "http://localhost:9200/_cat/shards/example?v"
# Show the index health
curl "http://localhost:9200/_cat/indices/example?v"Code language: PHP (php)
On a single-node cluster, _cat/shards returns output like this (IP, size and node name will differ):
index shard prirep state docs store ip node
example 0 p STARTED 0 249b 172.18.0.2 node-1
example 0 r UNASSIGNED
example 1 p STARTED 0 249b 172.18.0.2 node-1
example 1 r UNASSIGNEDCode language: CSS (css)
To find out why a shard isn't assigned, run curl "http://localhost:9200/_cluster/allocation/explain?pretty". To get a green index on a single node, set the replica count to zero (see the next section).
Changing shards and replicas after creation
number_of_replicas is a dynamic setting. You can change it on a live index at any time:
curl -X PUT "http://localhost:9200/example/_settings" \
-H 'Content-Type: application/json' \
-d '{"index": {"number_of_replicas": 0}}'Code language: JavaScript (javascript)
number_of_shards is fixed once the index exists. To change it, use one of these options:
- Split API (
POST /example/_split/example-4): creates a new index with more primaries. The target count must be a multiple of the source count, and the source index must be made read-only first. - Shrink API (
POST /example/_shrink/example-1): creates a new index with fewer primaries. The target count must be a factor of the source count, and a copy of every shard must sit on one node. - Reindex (
POST /_reindex): copies documents into a new index that you create with any settings. It's the most flexible option and the slowest.
Load sample data
Index a few documents with the bulk API so the queries below return results. The bulk body is newline-delimited JSON. It must end with a newline and be sent with --data-binary. If you use -d, curl strips the newlines and the request fails.
cat > docs.ndjson <<'EOF'
{"index":{"_id":"1"}}
{"title":"Install Elasticsearch on Ubuntu","category":"tutorial","views":1200,"published":"2024-03-10"}
{"index":{"_id":"2"}}
{"title":"Elasticsearch shard sizing guide","category":"guide","views":3400,"published":"2024-06-02"}
{"index":{"_id":"3"}}
{"title":"Kibana dashboards for beginners","category":"tutorial","views":800,"published":"2023-11-20"}
{"index":{"_id":"4"}}
{"title":"Logstash pipeline troubleshooting","category":"guide","views":150,"published":"2025-01-15"}
EOF
curl -X POST "http://localhost:9200/example/_bulk?refresh=true" \
-H 'Content-Type: application/x-ndjson' \
--data-binary @docs.ndjsonCode language: JavaScript (javascript)
No mapping was defined, so dynamic mapping decides the field types. title and category become text fields with a .keyword sub-field, views becomes long, and published becomes date. Check the result with GET /example/_mapping.
Popular Elasticsearch queries
All of these use GET /example/_search with a JSON body. Add ?pretty to the URL to get readable output.
# 1. match: full-text search on an analyzed field
curl -X GET "http://localhost:9200/example/_search?pretty" -H 'Content-Type: application/json' -d '{
"query": { "match": { "title": "elasticsearch guide" } }
}'
# 2. term: exact value on a keyword field
curl -X GET "http://localhost:9200/example/_search?pretty" -H 'Content-Type: application/json' -d '{
"query": { "term": { "category.keyword": "tutorial" } }
}'
# 3. range: numeric or date ranges
curl -X GET "http://localhost:9200/example/_search?pretty" -H 'Content-Type: application/json' -d '{
"query": { "range": { "published": { "gte": "2024-01-01", "lt": "2025-01-01" } } }
}'
# 4. bool: combine scored (must) and non-scored (filter) clauses
curl -X GET "http://localhost:9200/example/_search?pretty" -H 'Content-Type: application/json' -d '{
"query": {
"bool": {
"must": [ { "match": { "title": "elasticsearch" } } ],
"filter": [ { "range": { "views": { "gte": 1000 } } } ]
}
}
}'
# 5. Most popular documents: sort by views, return the top 3
curl -X GET "http://localhost:9200/example/_search?pretty" -H 'Content-Type: application/json' -d '{
"size": 3,
"sort": [ { "views": "desc" } ],
"_source": ["title", "views"]
}'
# 6. terms aggregation: document count and total views per category
curl -X GET "http://localhost:9200/example/_search?pretty" -H 'Content-Type: application/json' -d '{
"size": 0,
"aggs": {
"by_category": {
"terms": { "field": "category.keyword" },
"aggs": { "total_views": { "sum": { "field": "views" } } }
}
}
}'Code language: PHP (php)
| Query | Use it for | Scored |
|---|---|---|
match | Full-text search on text fields | Yes |
term / terms | Exact values on keyword, numeric or boolean fields | Yes, but usually placed in filter |
range | Numbers and dates | No, when used in filter |
bool | Combining clauses with must, should, must_not, filter | Only must and should |
terms aggregation | Top values and counts per group | Not applicable |
Note: Clauses inside filter don't affect scoring, and Elasticsearch can cache them. Put exact-match and range conditions there, and use must only for clauses that should change relevance.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Content-Type header [application/x-www-form-urlencoded] is not supported (406) | No JSON content type on the request | Add -H 'Content-Type: application/json' |
resource_already_exists_exception (400) | The index example already exists | Delete it with DELETE /example in a lab, or pick a new name |
curl: (52) Empty reply from server | Plain HTTP sent to an 8.x cluster with TLS turned on | Use https://, --cacert and -u elastic |
missing authentication credentials (401) | Security is on and no user was given | Pass -u user:password or an API key header |
term query returns no hits on category | category is an analyzed text field, so its value was lowercased and tokenized | Query category.keyword, or map the field as keyword |
| Index health is yellow | The replica can't be placed on the same node as its primary | Add a node, or set number_of_replicas to 0 on a single-node lab |
Shard sizing best practices
- Since Elasticsearch 7.0 the default is one primary shard per index. Add more only when data size or indexing throughput needs it.
- Elastic's general guidance is shard sizes of about 10GB to 50GB and no more than about 200 million documents per shard. Many small shards waste heap and cluster-state resources.
- For time-series data such as logs, use data streams or rollover with index lifecycle management (ILM) rather than one large index with many shards.
- Use at least one replica in production for high availability. Replicas can also serve search requests, which increases read throughput.
- Put shard and replica settings in an index template, so that every new index gets the same settings.
Frequently asked questions
What is the default number of shards in Elasticsearch?
Since Elasticsearch 7.0, a new index gets one primary shard and one replica by default. Older versions used five primary shards by default.
Can I change number_of_shards on an existing index?
No. The primary shard count is fixed when the index is created. To change it, use the split or shrink APIs, or reindex into a new index. The replica count can be changed at any time through _settings.
Why is my index yellow after creating it with one replica?
On a single-node cluster, the replica shards can't be assigned because Elasticsearch never places a replica on the same node as its primary. Add a second node, or set number_of_replicas to 0.
What is the difference between match and term queries?
A match query runs your input through the field's analyzer and searches full text. A term query looks for the exact value without analysis, so it belongs on keyword, numeric or date fields.
Why does my curl command fail with a 406 error?
Elasticsearch 6.0 and later require a Content-Type: application/json header on requests with a JSON body. Add -H 'Content-Type: application/json' to the curl command.
Related tutorials
- What is Elasticsearch and use cases of Elasticsearch?
- Top 50 Elasticsearch Interview Questions and Answers
- What is ELK Stack and use cases of ELK Stack?
- More Elastic Stack (ELK) tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals