Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 43 ยท Searching

Full-Text Queries

Learn Elasticsearch full-text queries: match, match_phrase, multi_match, operator, minimum_should_match, fuzziness and the caveats of query_string.

A term query looks for one exact token. That is rarely what a person typing into a search box wants. They type quick brown fox, they may misspell a word, and they expect the best documents first. Full-text queries exist for this. They run your text through the field's analyzer (see Analysis, Tokenizers and Analyzers), turn it into tokens, and then build a scored query from those tokens.

This lesson covers match, match_phrase, multi_match, the operator and minimum_should_match controls, fuzziness, and the two "query string" query types and why you should be careful with them. The real requests are read-only because no server runs here. Each idea also has a runnable JavaScript stand-in so you can see what the engine does with your words. The stand-ins are simplified; Lucene does much more.

Four full-text tools

match Analyze the text, match any or all tokens.
match_phrase Tokens must appear in order, side by side.
multi_match Search several fields at once.
fuzziness Tolerate typos by edit distance.

All of them analyze your query text first.

1 / 2

The match query

match is the default choice for searching a text field:

JSON
GET /articles/_search
{
  "query": {
    "match": {
      "title": "quick brown fox"
    }
  }
}

Elasticsearch analyzes quick brown fox with the analyzer of the title field. With the standard analyzer that gives three tokens: quick, brown, fox. By default the query becomes "quick OR brown OR fox". A document needs only one of the tokens to match, and documents that match more tokens (and rarer tokens) get a higher score. The scoring idea is explained in Relevance Scoring with BM25.

Because the query text is analyzed, Quick and quick match the same documents. Matching a keyword field is different: a match query on a keyword field uses the keyword analyzer, so the whole string must equal the stored value.

operator

The default is or. Set operator to and to require every token:

JSON
{
  "query": {
    "match": {
      "title": {
        "query": "quick brown fox",
        "operator": "and"
      }
    }
  }
}

Now a title must contain all three words, in any order and any position. and gives fewer, more precise results. or gives more recall.

minimum_should_match

There is a middle path. minimum_should_match says how many tokens must match. It accepts a number (2), a negative number (-1, all but one), or a percentage ("75%"):

JSON
{
  "query": {
    "match": {
      "title": {
        "query": "quick brown fox jumps",
        "minimum_should_match": "75%"
      }
    }
  }
}

With four tokens, 75% means three must match. Elasticsearch rounds the number down. This is a good default for long queries: it filters out documents that share only one common word but still tolerates one missing word.

match_phrase

Sometimes order matters. Searching for brown fox should not match "the fox is brown". match_phrase requires the tokens to appear in the same order at consecutive positions:

JSON
{
  "query": {
    "match_phrase": {
      "title": "brown fox"
    }
  }
}

This works because the inverted index stores token positions for text fields (see The Inverted Index). The slop parameter allows some looseness: "slop": 1 lets the tokens sit one move apart, so the phrase quick fox also matches "quick brown fox".

JSON
{
  "query": {
    "match_phrase": {
      "title": {
        "query": "quick fox",
        "slop": 1
      }
    }
  }
}

A related query, match_phrase_prefix, treats the last token as a prefix, which is handy for simple "search while typing" but is limited. Highlighting, Autocomplete and "Did You Mean" shows better tools.

Try it: phrase versus any-word matching

This stand-in keeps token positions like a real index and implements match with an operator, minimum_should_match and phrase matching with slop of zero. The scoring is just "number of matched tokens", which is much simpler than BM25.

JS match, minimum_should_match and match_phrase

Press Run (or Ctrl + Enter) to see the console output here.

No output.

multi_match

Users do not care which field a word lives in. multi_match runs one query text against several fields and lets you boost fields with ^:

JSON
{
  "query": {
    "multi_match": {
      "query": "elasticsearch tutorial",
      "fields": ["title^3", "summary", "body"],
      "type": "best_fields"
    }
  }
}

Here a hit in title counts three times as much as a hit in summary. The type decides how the per-field scores combine:

Type Idea Good for
best_fields (default) Use the score of the single best field Alternative wordings of the same thing (title vs body)
most_fields Add the scores of all fields The same text analyzed several ways (stemmed and unstemmed)
cross_fields Treat the fields as one big field A name split across first_name and last_name
phrase and phrase_prefix Run match_phrase on each field Order-sensitive search across fields
bool_prefix Terms match whole, the last one is a prefix Search-as-you-type fields

best_fields has a tie_breaker setting (between 0 and 1) that lets the other fields add a small share of their score. With tie_breaker: 0, only the best field counts. cross_fields needs operator: "and" for the "all words, in some field" behavior people expect; the next lesson, Bool Queries and Compound Logic, explains the dis_max query that best_fields is built on.

Fuzziness

People mistype. The fuzziness option matches terms within an edit distance. One edit is an insertion, deletion, substitution (and, by default, a swap of two adjacent letters):

JSON
{
  "query": {
    "match": {
      "title": {
        "query": "quik brwn fox",
        "fuzziness": "AUTO"
      }
    }
  }
}

AUTO picks the distance from the length of each term: 0 edits for 1-2 characters, 1 edit for 3-5 characters, and 2 edits for longer terms. That is a sensible choice because a one-edit change in a two-letter word can turn it into a completely different word.

Useful companions:

  • prefix_length: the first N characters must match exactly. Setting it to 1 or 2 makes fuzzy queries faster and removes many silly matches.
  • max_expansions: caps how many similar terms are considered (default 50).
  • transpositions: whether swapping two neighbors counts as one edit (default true).

Fuzziness is not free. Elasticsearch has to find all indexed terms close to each query term. Use it on small, well-chosen fields, and keep prefix_length above zero.

Try it: edit distance and AUTO fuzziness

The stand-in computes the Damerau-Levenshtein style distance (with adjacent swaps) and picks the AUTO allowance from term length, then checks it against a small vocabulary like the term dictionary of an index.

JS Fuzzy matching with AUTO

Press Run (or Ctrl + Enter) to see the console output here.

No output.

query_string and simple_query_string

Two queries accept a small search language written by the user: query_string and simple_query_string. They support operators such as AND, OR, quotes for phrases, - to exclude, * wildcards and field names.

JSON
{
  "query": {
    "query_string": {
      "query": "(quick AND fox) OR title:\"brown dog\"",
      "default_field": "title"
    }
  }
}

They are powerful, but be careful:

  • query_string has a strict syntax. A stray (, : or " in user input makes the whole request fail with a parse error, so never pass raw end-user input into it for a public search box.
  • Users can query fields you did not intend to expose (secret_notes:foo), or write expensive leading wildcards like *ing.
  • simple_query_string is the safer cousin: it never throws on bad syntax, supports only a limited set of operators (+, |, -, quotes, *, ~), and ignores what it does not understand. Pair it with an explicit fields list and default_operator.

For most applications, build a match or multi_match query yourself from the user's text. Reserve the query string types for power users, admin tools and internal log search. Security, Backups and Operations returns to safe handling of user input.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A match query for quick brown fox with the default settings finds which documents?

    The default operator is or, so one matching token is enough. More matching tokens and rarer tokens raise the score.
  2. 2. You want brown fox to match only when the words are next to each other in that order. Which query fits?

    match_phrase uses token positions from the index, so the tokens must appear in order at consecutive positions (or within slop).
  3. 3. What does fuzziness: AUTO do for a six-letter query term?

    AUTO allows 0 edits for 1-2 characters, 1 edit for 3-5 characters, and 2 edits for terms of 6 or more characters.
  4. 4. Why is simple_query_string usually safer than query_string for a public search box?

    query_string throws a parse error on bad syntax and exposes field names and wildcards. simple_query_string ignores what it cannot parse.
  5. 5. Which multi_match type fits a person's name split across first_name and last_name?

    cross_fields treats the fields as one combined field, so each word of the query may match in a different field.

Summary

  • match analyzes the query text and ORs the tokens by default; operator: and or minimum_should_match tightens it.
  • match_phrase needs tokens in order at consecutive positions, and slop loosens that.
  • multi_match searches several fields, with ^ boosts and a type that decides how scores combine.
  • fuzziness: AUTO tolerates typos based on term length; prefix_length keeps it fast and precise.
  • Treat query_string as a power-user tool; prefer simple_query_string or your own match queries for public input.

Next: Bool Queries and Compound Logic.