Bird
Raised Fist0
Elasticsearchquery~15 mins

Term query in Elasticsearch - Deep Dive

Choose your learning style10 modes available
Overview - Term query
What is it?
A term query in Elasticsearch is a way to find documents that contain an exact value in a specific field. It does not analyze or change the search word, so it looks for the exact match as stored. This is useful for searching keywords, IDs, or tags where you want precise results.
Why it matters
Without term queries, searching for exact values would be difficult, especially in large datasets. It solves the problem of finding precise matches quickly, which is important for filtering data like user IDs or status codes. Without it, searches would be slower or less accurate, making data retrieval frustrating.
Where it fits
Before learning term queries, you should understand basic Elasticsearch concepts like documents, fields, and indexing. After mastering term queries, you can learn about other query types like match queries, range queries, and how to combine queries for complex searches.
Mental Model
Core Idea
A term query finds documents by matching an exact value in a field without changing or analyzing the search term.
Think of it like...
It's like looking for a specific book by its exact ISBN number in a library catalog, not by the book's title or author.
┌───────────────┐
│ Elasticsearch  │
│   Index       │
│ ┌───────────┐ │
│ │ Documents │ │
│ └───────────┘ │
│   │           │
│   ▼           │
│ Term Query:   │
│ Find exact    │
│ value in field│
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Exact Match Search
🤔
Concept: Term query searches for exact values without changing the search word.
In Elasticsearch, some fields are analyzed (broken into parts) and some are not. Term query works on non-analyzed fields or keywords. For example, searching for the term 'Blue' will only find documents where the field exactly contains 'Blue', not 'blue' or 'blues'.
Result
You get documents where the field exactly matches the search term.
Understanding that term queries do not analyze the search term helps you know when to use them for precise filtering.
2
FoundationFields and Data Types Matter
🤔
Concept: Term queries work best on keyword or numeric fields, not full text fields.
Fields in Elasticsearch can be text (analyzed) or keyword (not analyzed). Term queries are designed for keyword fields or numbers. For example, searching a keyword field 'status' with term query 'active' finds exact matches, but using it on a text field may fail because text is analyzed into tokens.
Result
Term queries return correct results only on exact-match fields.
Knowing the field type prevents confusion when term queries return no results unexpectedly.
3
IntermediateUsing Term Query in JSON DSL
🤔Before reading on: do you think term query changes your search word to lowercase or splits it? Commit to your answer.
Concept: Term query syntax uses JSON to specify the field and exact value to match.
A term query looks like this: { "term": { "field_name": "value" } } For example, to find documents where 'user' is exactly 'alice', you write: { "term": { "user": "alice" } }
Result
Elasticsearch returns documents where 'user' field exactly equals 'alice'.
Understanding the JSON structure helps you write precise queries and avoid syntax errors.
4
IntermediateDifference Between Term and Match Queries
🤔Before reading on: do you think term query and match query behave the same on text fields? Commit to your answer.
Concept: Term query does exact matching; match query analyzes the search text before matching.
Match query breaks the search text into tokens and applies analysis like lowercasing. Term query does not analyze and looks for exact value. For example, searching 'Quick Brown' with match query finds documents with 'quick' or 'brown', but term query looks for the exact phrase 'Quick Brown' as stored.
Result
Term query returns fewer, exact matches; match query returns broader, analyzed matches.
Knowing this difference helps you choose the right query type for your search needs.
5
IntermediateTerm Query with Numeric and Boolean Fields
🤔
Concept: Term queries work on numbers and booleans by matching exact values.
You can use term queries to find documents where a numeric field equals a number or a boolean field equals true/false. For example: { "term": { "age": 30 } } finds documents where 'age' is exactly 30.
Result
Documents with the exact numeric or boolean value are returned.
Term queries are versatile and not limited to text fields; they work well for exact numeric or boolean filtering.
6
AdvancedTerm Query Performance and Caching
🤔Before reading on: do you think term queries are slower than match queries? Commit to your answer.
Concept: Term queries are fast because they use inverted indexes and can be cached efficiently.
Elasticsearch stores terms in an inverted index, which maps terms to documents. Term queries look up the exact term quickly. Also, Elasticsearch caches frequent term queries to speed up repeated searches.
Result
Term queries execute quickly and scale well on large datasets.
Understanding performance helps you optimize search speed and resource use in production.
7
ExpertTerm Query and Keyword Normalization Pitfalls
🤔Before reading on: do you think term query automatically handles case differences or accents? Commit to your answer.
Concept: Term queries do not normalize keywords; exact stored value must match search term exactly, including case and accents.
If your keyword field stores 'Café' with an accent, searching with term query 'Cafe' (no accent) returns no results. Similarly, 'Blue' and 'blue' are different. To handle this, you must preprocess data or use normalizers at index time.
Result
Term queries can miss matches if data normalization is not handled properly.
Knowing this prevents subtle bugs where expected matches are missing due to exact matching rules.
Under the Hood
Elasticsearch builds an inverted index for each field, mapping each unique term to the documents containing it. Term queries directly look up the exact term in this index without analyzing or modifying the search term. This direct lookup is fast and precise. The inverted index is stored in a way that allows quick retrieval of document IDs matching the term.
Why designed this way?
Term queries were designed to provide exact matching for fields where analysis would be inappropriate or harmful, such as IDs, tags, or keywords. This design allows Elasticsearch to support both full-text search (analyzed) and exact filtering (non-analyzed) efficiently. Alternatives like analyzing all fields would slow down exact lookups and reduce precision.
┌───────────────┐
│ Document Store│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Inverted Index │
│ ┌───────────┐ │
│ │ Term 'X'  │─┼─► Document IDs containing 'X'
│ └───────────┘ │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Term Query    │
│ Looks up term │
│ in index      │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does term query analyze the search term before matching? Commit to yes or no.
Common Belief:Term query analyzes the search term like match query does.
Tap to reveal reality
Reality:Term query does NOT analyze the search term; it matches the exact stored value.
Why it matters:Assuming analysis happens leads to no results when searching text fields with term query.
Quick: Can term query find partial matches inside a text field? Commit to yes or no.
Common Belief:Term query can find partial or fuzzy matches inside text fields.
Tap to reveal reality
Reality:Term query only finds exact matches; it does not support partial or fuzzy matching.
Why it matters:Using term query expecting partial matches causes missed results and confusion.
Quick: Does term query ignore case differences automatically? Commit to yes or no.
Common Belief:Term query ignores case differences and matches regardless of uppercase or lowercase.
Tap to reveal reality
Reality:Term query matches exactly, including case; 'Blue' and 'blue' are different terms.
Why it matters:Ignoring case sensitivity causes unexpected empty results or missed documents.
Quick: Can term query be used on analyzed text fields effectively? Commit to yes or no.
Common Belief:Term query works well on analyzed text fields for exact matches.
Tap to reveal reality
Reality:Term query is ineffective on analyzed text fields because the stored terms are tokenized and may not match the exact search term.
Why it matters:Using term query on analyzed fields leads to no matches and wasted debugging time.
Expert Zone
1
Term queries on keyword fields can be combined with normalizers to handle case or accent normalization, but this must be set up at index time.
2
Using term queries inside filters improves performance because filters are cached and do not affect scoring.
3
Term queries can be combined with scripts or runtime fields for dynamic exact matching, but this impacts performance.
When NOT to use
Avoid term queries when searching full-text fields where you want partial, fuzzy, or analyzed matches. Use match queries or multi-match queries instead. Also, avoid term queries if you need case-insensitive search on keyword fields without normalization.
Production Patterns
In production, term queries are often used for filtering by exact IDs, tags, status codes, or boolean flags. They are combined with bool queries to build complex filters. Caching of term queries is leveraged for repeated filters like user roles or categories.
Connections
Hash Tables
Term queries use inverted indexes, which are similar in concept to hash tables mapping keys to values.
Understanding hash tables helps grasp how term queries quickly find documents by exact keys (terms).
Set Theory
Term queries select documents as sets containing a specific element (term), similar to set membership in math.
Knowing set membership clarifies how term queries filter documents precisely by presence of a term.
Library Cataloging Systems
Term queries resemble searching a library catalog by exact call number or ISBN, not by keywords or topics.
This connection shows how exact matching is essential for precise retrieval in many systems beyond search engines.
Common Pitfalls
#1Using term query on analyzed text fields expecting full-text search.
Wrong approach:{ "term": { "description": "quick brown fox" } }
Correct approach:{ "match": { "description": "quick brown fox" } }
Root cause:Misunderstanding that term query does not analyze text and only matches exact stored tokens.
#2Searching keyword fields with wrong case in term query.
Wrong approach:{ "term": { "status": "active" } } // but stored as 'Active'
Correct approach:{ "term": { "status": "Active" } }
Root cause:Not realizing term query is case sensitive and requires exact match.
#3Expecting partial matches with term query.
Wrong approach:{ "term": { "tags": "blue" } } // but document has 'blueberry'
Correct approach:{ "match": { "tags": "blue" } }
Root cause:Confusing exact term matching with full-text or partial matching capabilities.
Key Takeaways
Term query finds documents by matching exact values in fields without analyzing the search term.
It works best on keyword, numeric, or boolean fields where exact matching is needed.
Term queries are fast because they use inverted indexes and caching for quick lookups.
They do not handle case differences, accents, or partial matches automatically.
Choosing between term and match queries depends on whether you want exact or analyzed search.

Practice

(1/5)
1. What does a term query in Elasticsearch do?
easy
A. Analyzes and breaks the search term into tokens
B. Finds exact matches of the given term in the data
C. Finds documents with terms similar to the search term
D. Sorts documents based on the term frequency

Solution

  1. Step 1: Understand the purpose of term query

    A term query searches for exact matches without analyzing the search term.
  2. Step 2: Compare options with term query behavior

    Only Finds exact matches of the given term in the data describes exact matching, which is the core of term query.
  3. Final Answer:

    Finds exact matches of the given term in the data -> Option B
  4. Quick Check:

    Term query = exact match [OK]
Hint: Term query matches exactly, no analysis or tokenizing [OK]
Common Mistakes:
  • Confusing term query with match query that analyzes text
  • Thinking term query sorts results
  • Assuming term query finds similar or partial matches
2. Which of the following is the correct syntax for a term query in Elasticsearch?
easy
A. { "terms": { "user": ["kimchy"] } }
B. { "match": { "user": "kimchy" } }
C. { "term_query": { "user": "kimchy" } }
D. { "term": { "user": "kimchy" } }

Solution

  1. Step 1: Identify correct term query syntax

    The term query uses the key "term" with a field and exact value.
  2. Step 2: Check each option

    { "term": { "user": "kimchy" } } matches the correct syntax. { "match": { "user": "kimchy" } } is a match query, C is invalid, D is a terms query (plural) for multiple values.
  3. Final Answer:

    { "term": { "user": "kimchy" } } -> Option D
  4. Quick Check:

    Term query syntax = { "term": { "user": "kimchy" } } [OK]
Hint: Term query uses "term" key with field and exact value [OK]
Common Mistakes:
  • Using "match" instead of "term" for exact match
  • Confusing "term" with "terms" for single value
  • Adding extra keys like "term_query" which is invalid
3. Given this Elasticsearch query:
{ "query": { "term": { "status": "active" } } }

What documents will this query return?
medium
A. Documents where the status field exactly equals "active"
B. Documents where the status field contains the word "active" anywhere
C. Documents where the status field starts with "active"
D. Documents where the status field is analyzed and matches "active"

Solution

  1. Step 1: Understand term query behavior on field

    The term query matches documents where the field value exactly equals the given term without analysis.
  2. Step 2: Analyze each option

    Only Documents where the status field exactly equals "active" correctly describes exact equality. Others describe partial or analyzed matches which term query does not do.
  3. Final Answer:

    Documents where the status field exactly equals "active" -> Option A
  4. Quick Check:

    Term query = exact field value match [OK]
Hint: Term query matches exact field value only [OK]
Common Mistakes:
  • Thinking term query matches partial or analyzed text
  • Assuming term query matches prefixes or substrings
  • Confusing term query with match query behavior
4. You wrote this term query but it returns no results:
{ "query": { "term": { "user": "Kimchy" } } }

Your data has the user field stored as lowercase "kimchy". What is the problem?
medium
A. Term query is case sensitive and "Kimchy" does not match "kimchy"
B. The term query syntax is incorrect
C. The user field is missing in the documents
D. Term query analyzes the term and changes case

Solution

  1. Step 1: Understand term query case sensitivity

    Term query matches exact terms and is case sensitive, so "Kimchy" does not match "kimchy".
  2. Step 2: Check other options

    Syntax is correct, field exists, and term query does not analyze or change case.
  3. Final Answer:

    Term query is case sensitive and "Kimchy" does not match "kimchy" -> Option A
  4. Quick Check:

    Term query = exact case match [OK]
Hint: Term query matches exact case; check letter casing [OK]
Common Mistakes:
  • Assuming term query ignores case
  • Thinking syntax error causes no results
  • Believing term query analyzes or lowercases terms
5. You want to find documents where the tags field contains exactly the term urgent. The tags field is an array of keywords. Which query is best to use?
hard
A. { "match": { "tags": "urgent" } }
B. { "terms": { "tags": "urgent" } }
C. { "term": { "tags": "urgent" } }
D. { "term": { "tags.keyword": "urgent" } }

Solution

  1. Step 1: Understand term query on array fields

    Term query matches exact terms in arrays, so it works directly on the tags field.
  2. Step 2: Evaluate other options

    Match query analyzes text (not exact). Terms query expects multiple values to match any. Using tags.keyword is unnecessary if tags is keyword type.
  3. Final Answer:

    { "term": { "tags": "urgent" } } -> Option C
  4. Quick Check:

    Term query matches exact term in array [OK]
Hint: Use term query for exact keyword in array fields [OK]
Common Mistakes:
  • Using match query which analyzes and may not match exactly
  • Using terms query incorrectly for single term
  • Confusing field type and using .keyword unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard