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.
| Aspect | URI search (?q=) | Request body (Query DSL) |
|---|---|---|
| Example | ?q=state:kentucky&sort=age:asc | {"query":{"match":{"state":"kentucky"}}} |
| Best for | Quick checks from a browser or the shell | Applications, complex bool logic, aggregations |
| Features | q, sort, from, size, explain, _source | All query types, aggregations, highlighting, search_after |
| Pitfalls | Special characters need URL encoding; bad syntax returns a parse error | More 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.valuewithrelation: eq: the exact number of matches.gtemeans the count was capped, at 10,000 by default._score: the relevance score. If you sort on a field such asage, scores are not calculated and come back asnull, unless you also sort by_scoreor settrack_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.
| Setting | Result with the sample data |
|---|---|
"_source": false | Only 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 symptom | Cause | Fix |
|---|---|---|
Content-Type header [application/x-www-form-urlencoded] is not supported | Body sent without a JSON header | Add -H 'Content-Type: application/json' |
curl: (52) Empty reply from server or missing authentication credentials | 8.x cluster with security enabled | Use https:// with -u and --cacert, or use Kibana Dev Tools |
Text fields are not optimised for operations that require per-document field data | Sorting on a text field | Sort on the .keyword sub-field or a numeric field |
Result window is too large | from + size is more than 10,000 | Use search_after with a point in time |
term query returns 0 hits | Case or multi-word value against an analyzed field | Use match, or term on .keyword |
index_not_found_exception | Index name typo or data not loaded | Check 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
- What is Elasticsearch and use cases of Elasticsearch?
- Top 50 Elasticsearch Interview Questions and Answers
- 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