☕ 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#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 through pagination, sorting, explain, term queries, multi-index search and _source filtering. Below the original commands you will find sample data to run them against, an explanation of each technique and fixes for the commands that no longer work on Elasticsearch 7.x and 8.x.

Reference

  • Sample Data & Query – https://github.com/devopsschool-demo-labs-projects/elasticsearch

Before you start: cluster access and sample data

The commands above use plain http://localhost:9200 with no authentication. That works on an Elasticsearch 7.x lab node that has security turned off. On Elasticsearch 8.x, security and TLS are on by default, so every request needs HTTPS and credentials. Either add the options below to each curl command, or paste the request part (for example GET /customers/_search) into Kibana Dev Tools, which handles authentication for you.

# Elasticsearch 8.x with default security
export ES='https://localhost:9200'
curl -u elastic:$ELASTIC_PASSWORD --cacert http_ca.crt "$ES/_cluster/health?pretty"

# Lab only: skip certificate verification
curl -k -u elastic:$ELASTIC_PASSWORD "$ES/customers/_search?pretty"Code language: PHP (php)

The repository linked above has the full sample data set. If you only want to try the queries, the small customers index below is enough. Dynamic mapping turns each string field into text with a keyword sub-field (for example state.keyword) and turns age into a long.

cat > customers.ndjson <<'EOF'
{"index":{"_id":"1"}}
{"name":"Bill Gates","street":"12 Chestnut Street","city":"Seattle","state":"Washington","age":45,"gender":"male"}
{"index":{"_id":"2"}}
{"name":"Anna Brooks","street":"88 Oak Avenue","city":"Cheyenne","state":"Wyoming","age":31,"gender":"female"}
{"index":{"_id":"3"}}
{"name":"Tom Reed","street":"5 Chestnut Lane","city":"Louisville","state":"Kentucky","age":52,"gender":"male"}
{"index":{"_id":"4"}}
{"name":"Maria Lopez","street":"301 Pine Road","city":"Lexington","state":"Kentucky","age":27,"gender":"female"}
EOF

curl -XPOST 'localhost:9200/customers/_bulk?refresh&pretty' \
  -H 'Content-Type: application/x-ndjson' --data-binary @customers.ndjsonCode language: JavaScript (javascript)

Note: Use --data-binary, not -d, for bulk files. -d strips newlines, and the bulk API needs every line, including the last one, to end with a newline. The refresh parameter makes the documents searchable straight away.

URI search versus request body search

Both styles call the same _search endpoint. ?q= uses Lucene query string syntax. With no field prefix it searches every eligible field, because index.query.default_field defaults to *. The request body uses the full Query DSL, and that is what you will use in real applications.

AspectURI search (?q=)Request body (Query DSL)
Example?q=state:kentucky&sort=age:asc{"query":{"match":{"state":"kentucky"}}}
Best forQuick checks from a browser or the shellApplications, complex bool logic, aggregations
Featuresq, sort, from, size, explain, _sourceAll query types, aggregations, highlighting, search_after
PitfallsSpecial characters need URL encoding; bad syntax returns a parse errorMore verbose; needs a Content-Type: application/json header

GET and POST behave the same on _search. Some HTTP clients and proxies drop the body of a GET request. If that happens, send the same JSON with POST.

Reading the search response

Every search returns the same structure. In Elasticsearch 7.0 and later, hits.total is an object, not a plain number.

{
  "took" : 3,
  "timed_out" : false,
  "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 },
  "hits" : {
    "total" : { "value" : 2, "relation" : "eq" },
    "max_score" : 0.87,
    "hits" : [
      { "_index" : "customers", "_id" : "3", "_score" : 0.87,
        "_source" : { "name" : "Tom Reed", "state" : "Kentucky", "age" : 52 } }
    ]
  }
}Code language: JSON / JSON with Comments (json)
  • took: how long the search took, in milliseconds.
  • hits.total.value with relation: eq: the exact number of matches. gte means the count was capped, at 10,000 by default.
  • _score: the relevance score. If you sort on a field such as age, scores are not calculated and come back as null, unless you also sort by _score or set track_scores.
  • _source: the original JSON document. This is what source filtering trims.

Pagination, sorting and the explain parameter

size sets how many hits come back. The default is 10. from sets how many hits to skip, so page N has from = (N - 1) * size. By default from + size cannot be more than 10,000, the index.max_result_window setting. To page deeper, use search_after with a point in time instead of raising that limit.

The ???? in the example above is next to the explain commands. explain=true adds an _explanation object to every hit, showing how the score was calculated (BM25 term frequency, inverse document frequency and field length). Use it to debug relevance, not in production queries, because it adds overhead.

curl -XGET 'localhost:9200/customers/_search?q=state:kentucky&explain=true&pretty'

# Explain one document against a query
curl -XGET 'localhost:9200/customers/_explain/3?pretty' -H 'Content-Type: application/json' -d'
{ "query": { "match": { "state": "kentucky" } } }'Code language: PHP (php)

Note: Sort on numeric, date or keyword fields. Sorting on a text field such as state fails with a fielddata error. Use state.keyword instead.

Term versus match: why some term queries return nothing

A term query looks for the exact token you give it and does not analyze the input. String fields are analyzed when they are indexed: the standard analyzer lowercases text and splits it into words. So "term": {"name": "gates"} matches "Bill Gates", but "term": {"name": "Gates"} and "term": {"name": "bill gates"} match nothing. The term examples above only work because their values are single lowercase words.

# Full-text search on a text field: input is analyzed, so case does not matter
curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{ "query": { "match": { "name": "Bill Gates" } } }'

# Exact match on the keyword sub-field: case and spacing must match exactly
curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{ "query": { "term": { "state.keyword": "Washington" } } }'Code language: PHP (php)

Rule of thumb: use match for human-entered text, and use term or terms for IDs, status codes, tags and .keyword fields.

How source filtering works

Source filtering only changes which parts of _source are returned. It does not change which documents match or how they are scored. Wildcards are matched against field names.

SettingResult with the sample data
"_source": falseOnly metadata (_index, _id, _score) is returned. Useful when you only need IDs or counts.
"_source": "st*"Returns street and state.
"_source": ["st*", "*n*"]Adds every field whose name contains n: name and gender.
includes + excludes: ["*der"]Same as the line above, but gender is removed. Excludes win over includes.

To return values from the index instead of from _source, for example dates in a particular format, use the fields parameter: "fields": ["state.keyword", "age"].

Corrected commands for Elasticsearch 7.x and 8.x

Two commands in the example above no longer work as written on current versions.

Searching multiple document types. Mapping types were deprecated in 7.x and removed in 8.x, so products/shoes,laptops/_search cannot target types. Either store each kind of product in its own index, or keep one index and filter on a field:

# Option 1: one index per product kind
curl -XGET 'localhost:9200/shoes,laptops/_search?pretty'

# Option 2: one index with a category field
curl -XGET 'localhost:9200/products/_search?pretty' -H 'Content-Type: application/json' -d'
{ "query": { "terms": { "category.keyword": ["shoes", "laptops"] } } }'Code language: PHP (php)

Empty query object. {"query": {}} is not a valid query clause, and current versions reject it with a parsing error. To return all documents, use match_all or leave out query entirely:

curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{ "query": { "match_all": {} } }'

# Same result, no body
curl -XGET 'localhost:9200/customers/_search?pretty'Code language: PHP (php)

Common errors and fixes

Error or symptomCauseFix
Content-Type header [application/x-www-form-urlencoded] is not supportedBody sent without a JSON headerAdd -H 'Content-Type: application/json'
curl: (52) Empty reply from server or missing authentication credentials8.x cluster with security enabledUse https:// with -u and --cacert, or use Kibana Dev Tools
Text fields are not optimised for operations that require per-document field dataSorting on a text fieldSort on the .keyword sub-field or a numeric field
Result window is too largefrom + size is more than 10,000Use search_after with a point in time
term query returns 0 hitsCase or multi-word value against an analyzed fieldUse match, or term on .keyword
index_not_found_exceptionIndex name typo or data not loadedCheck with GET _cat/indices?v

Frequently asked questions

What is the difference between query and filter context in Elasticsearch?

Clauses in query context calculate a relevance score. Clauses in filter context, such as bool.filter, only decide whether a document matches, and their results can be cached. Put exact conditions like status, ranges and keyword matches in filters, and put full-text search in the query.

Should I use GET or POST for _search with a request body?

Elasticsearch handles both the same way. Use POST if your HTTP client, proxy or load balancer drops bodies on GET requests.

Why does my term query return no results when the document clearly contains the value?

The field is probably text, which was lowercased and split into tokens at index time, while term looks for your exact input. Use a match query, or run the term query against the .keyword sub-field with the exact original value.

How do I get more than 10,000 search results?

Do not page past 10,000 with from and size. Use search_after together with a point in time (PIT) for deep pagination, or the scroll API for one-off exports in older setups.

Is the ?q= URI search safe to use in applications?

It suits quick checks, but user input passed into Lucene query string syntax can cause parse errors or expensive wildcard queries. Applications should build Query DSL bodies, or use simple_query_string, which handles bad syntax more gracefully.

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#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…

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#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