☕ 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#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 the term query, how to run them on a secured Elasticsearch 8.x cluster, the most useful extra options (operator, minimum_should_match, fuzziness, slop, max_expansions), and how to work out why a query returns no hits.

Reference

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

Term vs match: why analysis decides the result

The gist opens with "TERM VS MATCH" but only shows the match family. The difference comes down to analysis. When a document is indexed, a text field such as name goes through an analyzer. With the default standard analyzer, Frank Norris is stored as the lowercase tokens frank and norris. A match query runs the same analyzer on your search text before it looks up tokens. A term query skips analysis and looks for the exact value you typed.

QuerySearch text analyzed?Typical field typeUse it for
termNokeyword, numbers, dates, booleansExact values: IDs, status codes, tags
matchYestextFull-text search where any or all words should match
match_phraseYestextWords that must appear together and in order
match_phrase_prefixYes, last word treated as a prefixtextSimple search-as-you-type on small data sets

Run these two queries to see the difference. The first usually returns no hits, because the inverted index holds webster, not Webster. The second searches the keyword sub-field that dynamic mapping creates for strings, which stores the original value as one exact token. The full value has to match, so replace Webster with a complete name from your data.

# term on an analyzed text field: usually 0 hits
curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": { "term": { "name": "Webster" } }
}'

# term on the keyword sub-field: exact, case-sensitive full value
curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": { "term": { "name.keyword": "Webster" } }
}'Code language: PHP (php)

Note: The name.keyword sub-field only exists if the index used dynamic mapping or an explicit multi-field mapping. Check with GET customers/_mapping before you rely on it.

Running the queries on Elasticsearch 8.x and later

The curl commands in the gist assume a cluster with no security, served over plain HTTP. That was the default in older releases. Since Elasticsearch 8.0, security is on by default: the HTTP layer uses TLS and every request needs credentials. On a default 8.x install, add https, the CA certificate and a user:

export ES_URL=https://localhost:9200
export ELASTIC_PASSWORD='your-password'

curl --cacert /path/to/http_ca.crt -u elastic:$ELASTIC_PASSWORD \
  -XGET "$ES_URL/customers/_search?pretty" \
  -H 'Content-Type: application/json' -d'
{
  "query": { "match": { "name": "webster" } }
}'Code language: PHP (php)

In a lab you can use -k instead of --cacert to skip certificate checks. Never do that against a production cluster. A simpler option is Kibana Dev Tools > Console, which handles authentication for you. Paste only the method, path and body:

GET customers/_search
{
  "query": { "match": { "name": "webster" } }
}Code language: JavaScript (javascript)

In each response, check hits.total.value for the number of matches and _score on each hit for relevance. Results are sorted by _score, highest first, unless you add a sort clause.

Getting more out of match

In the examples above, operator: or (the default) returns customers whose name contains frank or norris. Documents that contain both words score higher. With operator: and, both tokens must be present. minimum_should_match sits between the two, and fuzziness tolerates typos.

# At least 2 of the 3 words must match
curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "street": {
        "query": "tompkins place avenue",
        "minimum_should_match": 2
      }
    }
  }
}'

# Typo tolerance: "webstr" still finds "webster"
curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "name": { "query": "webstr", "fuzziness": "AUTO" }
    }
  }
}'Code language: PHP (php)
  • minimum_should_match accepts a number (2) or a percentage ("75%").
  • fuzziness: AUTO allows edits based on term length: none for very short terms, one edit for medium terms and two for longer terms.
  • A match query targets one field. To search several fields at once, use multi_match with a fields array.

match_phrase and slop

match_phrase requires every token to be present and in the same order, next to each other. That is why match on tompkins place returns any street containing place, while match_phrase returns only streets that contain the exact phrase. Use slop to allow other words in between, or the terms in a different order:

curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "match_phrase": {
      "street": { "query": "tompkins place", "slop": 1 }
    }
  }
}'Code language: PHP (php)

slop is the number of position moves allowed. slop: 1 lets one extra word sit between tompkins and place. Swapping the two words takes a slop of 2. Higher values match more loosely and cost more to run.

match_phrase_prefix and its limits

match_phrase_prefix works like match_phrase, except the last token is treated as a prefix. In clymer st, clymer must match exactly and st can expand to street, st and so on. Elasticsearch expands the prefix into at most max_expansions terms (default 50), so on large indices some valid matches can be missed silently.

curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "match_phrase_prefix": {
      "name": { "query": "ma", "max_expansions": 10 }
    }
  }
}'Code language: PHP (php)

Note: Use match_phrase_prefix for quick labs and small data sets. For production autocomplete, use a search_as_you_type field or the completion suggester. Both are built for prefix matching and give complete, predictable results.

Finding out why a query does or does not match

When results look wrong, look at the tokens Elasticsearch actually stores. The _analyze API runs a field's analyzer on any text, and explain shows how each hit's score was calculated.

# Which tokens does the street field produce?
curl -XGET 'localhost:9200/customers/_analyze?pretty' -H 'Content-Type: application/json' -d'
{ "field": "street", "text": "Tompkins Place" }'

# Field types and sub-fields
curl -XGET 'localhost:9200/customers/_mapping?pretty'

# Scoring details per hit
curl -XGET 'localhost:9200/customers/_search?pretty' -H 'Content-Type: application/json' -d'
{ "explain": true, "query": { "match": { "name": "frank norris" } } }'Code language: PHP (php)

With the standard analyzer, _analyze returns the tokens tompkins and place, both lowercase. If your term value differs from these tokens, it will not match.

Common errors and fixes

SymptomCauseFix
curl: (52) Empty reply from serverPlain HTTP sent to an 8.x node that has TLS enabledUse https:// and --cacert (or -k in a lab)
security_exception with status 401No credentials or wrong credentialsAdd -u elastic:password or an API key header
Content-Type header [...] is not supported, status 406The -H 'Content-Type: application/json' header is missingAlways send the JSON content type with a body
index_not_found_exception, status 404The sample data is not loaded, or the index name is wrongLoad the data from the reference repo, then check with GET _cat/indices
parsing_exception: match doesn't support multiple fieldsTwo fields placed inside one matchUse multi_match or a bool query with several match clauses
term returns 0 hitsSearching a text field, which holds analyzed, lowercase tokensUse match, or term on the .keyword sub-field

Corrections to the original

  • The comment ----DEFAUL OPERATOR IS or should read "default operator is or". It refers to the match query that follows it, which sends no operator.
  • The heading "TERM VS MATCH" has no term example under it. The first section above adds one and explains the difference.
  • The curl commands target http://localhost:9200 with no credentials. That only works on clusters with security disabled. On a default Elasticsearch 8.x or later install, use https, a CA certificate and a username and password, as shown above.

Frequently asked questions

What is the difference between match and term in Elasticsearch?

match analyzes your search text with the field's analyzer before it looks up tokens, so it suits full-text text fields. term looks up the exact value without analysis, so it suits keyword, numeric and date fields.

What is the default operator of the match query?

The default is or. A document matches if any of the analyzed words is present. Set operator to and to require all words, or use minimum_should_match for a middle ground.

When should I use match_phrase instead of match?

Use match_phrase when the words must appear together and in the same order, such as a street name or a state like puerto rico. Add slop if you want to allow a few words in between.

Why does match_phrase_prefix miss some results?

The last word is expanded into at most max_expansions matching terms (50 by default), so other valid completions are left out. For autocomplete, use a search_as_you_type field or the completion suggester.

Can I use GET with a request body in curl for Elasticsearch?

Yes. Elasticsearch accepts the _search body with either GET or POST. -XGET -d works in curl, and POST is a safe alternative for clients that drop GET bodies.

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