Search basics and the match query

Elasticsearch · Essentials · 10 min

Full-text search with relevance ranking is the reason Elasticsearch exists.

GET /index/_search with a query returns ranked hits. The workhorse full-text query is match: { "match": { "name": "blue pens" } } analyzes the query text into terms (blue, pens, lower-cased) and finds documents containing any of them, scoring documents with more and rarer matches higher.

The response contains:

  • hits.total: the number of matches (counted exactly up to 10,000 by default, then reported as a lower bound with "relation": "gte"),
  • hits.hits: the top results, each with _id, _score and _source,
  • took in milliseconds and timed_out.

Useful options on match: "operator": "and" to require all terms, "fuzziness": "AUTO" to tolerate typos, minimum_should_match for "at least 2 of 3 words". multi_match searches several fields at once, e.g. ["name^3", "description"] where ^3 boosts name matches.

Control the response with size (default 10), _source filtering ("_source": ["name", "price"]) or fields, and highlight to get matched fragments wrapped in tags.

A search with no query, or { "match_all": {} }, returns everything with score 1.0. GET /index/_count returns just the number of matches.

Example

GET /products/_search
{
  "query": {
    "match": { "name": { "query": "blue pens", "operator": "or", "fuzziness": "AUTO" } }
  },
  "_source": ["name", "price"],
  "size": 3,
  "highlight": { "fields": { "name": {} } }
}
# "hits": {
#   "total": { "value": 2, "relation": "eq" },
#   "hits": [
#     { "_id": "1", "_score": 1.38, "_source": { "name": "Blue pen", "price": 1.2 },
#       "highlight": { "name": ["<em>Blue</em> <em>pen</em>"] } },
#     { "_id": "4", "_score": 0.54, "_source": { "name": "Blue notebook", "price": 4 } } ] }

Remember

  • match analyzes the query text and ranks by relevance (_score)
  • operator: and, fuzziness and minimum_should_match tune matching
  • multi_match with ^boost searches several fields
  • size, _source filtering and highlight shape the response

Watch out for

  • Reading hits.total as exact for large result sets: beyond 10,000 it is a lower bound unless track_total_hits is true.

Check yourself

  1. A match query for "red shoes" uses the default operator. Which documents match?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html