☕ XOPSSCHOOL — LEARNING MADE AFFORDABLE
Build the Skills Your Next Career Move Demands.
For the Price of One Coffee a Month.
Why spend hundreds on individual courses? Unlock an entire year of technical learning with one Coffee Pass.
US$4.90 /month
US$58.80/year
₹499 + GST/month
₹5,988 + GST/year
€4.90 /month
€58.80/year
12 Months of Access • Billed Annually • No Automatic Renewal
DevOps • Cloud • SRE • Kubernetes • Terraform • DevSecOps • AI • AIOps • MLOps • LLMOps • FinOps • GitOps • Platform Engineering & Much More
192
Premium Courses
1,085
Video Sessions
99
Ops Disciplines
86
Tool Courses
340
Assignments
227
Quizzes
✓ QR-Verifiable Certificates   ✓ Learn at Your Own Pace   ✓ Hands-on Learning   ✓ New Courses Included
Learn from real-world, instructor-led video sessions by
Rajesh Kumar
Principal Architect • Trainer • Mentor • 15+ Years of Industry Experience
☕ Get My Coffee Pass — Start Learning Today →
One Payment. Every Premium Course. One Full Year.
The best investment you can make is in the person you are becoming.

Elasticsearch Lab#5 – Example of Popular Query

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)
QueryUse it forScored
matchFull-text search on text fieldsYes
term / termsExact values on keyword, numeric or boolean fieldsYes, but usually placed in filter
rangeNumbers and datesNo, when used in filter
boolCombining clauses with must, should, must_not, filterOnly must and should
terms aggregationTop values and counts per groupNot 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

ErrorCauseFix
Content-Type header [application/x-www-form-urlencoded] is not supported (406)No JSON content type on the requestAdd -H 'Content-Type: application/json'
resource_already_exists_exception (400)The index example already existsDelete it with DELETE /example in a lab, or pick a new name
curl: (52) Empty reply from serverPlain HTTP sent to an 8.x cluster with TLS turned onUse https://, --cacert and -u elastic
missing authentication credentials (401)Security is on and no user was givenPass -u user:password or an API key header
term query returns no hits on categorycategory is an analyzed text field, so its value was lowercased and tokenizedQuery category.keyword, or map the field as keyword
Index health is yellowThe replica can't be placed on the same node as its primaryAdd 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals

Related Posts

Elasticsearch templates

An Elasticsearch index template holds the settings, mappings and aliases that Elasticsearch applies when it creates a new index or data stream backing index whose name matches…

Read More

Elasticsearch Lab#4 – DSL Query Collection Part#2

This lab covers the Elasticsearch full-text queries match, match_phrase and match_phrase_prefix, using the customers sample index. Below the gist you will find how these queries differ from…

Read More

Elasticsearch Lab#3 – DSL Query Collection Part#1

This lab covers the two ways to send a search to Elasticsearch's _search API: URI query parameters (?q=) and a JSON Query DSL request body. It goes…

Read More

Elasticsearch Lab#2 – Bulk indexing document using mget & bulk api

This lab uses the Elasticsearch _mget API to fetch several documents in one request and the _bulk API to index, create, update and delete many documents in…

Read More

Elastic Tutorial: Elasticsearch 8.X Installation & CRUD in Linux

This page shows how to install Elasticsearch 8.x from the official tar.gz archive on Linux, start it as a non-root user, and connect over HTTPS with the…

Read More

How to configure Elastic filebeat 8.3 with Elasticseach?

This guide shows how to install Filebeat 8.3 from the tarball, collect log files with the filestream input, and send them to an Elasticsearch 8 cluster that…

Read More