The Query DSL: Domain Specific Language
8 min read
Course: Elasticsearch
The Query DSL: Domain Specific Language
Welcome to the heart of Elasticsearch. If Elasticsearch is an incredibly fast, highly organized library, then the Query DSL (Domain Specific Language) is the exact vocabulary you must use to ask the librarian for books.
When you first start with Elasticsearch, you might be tempted to use simple query strings directly in the URL (like GET /users/_search?q=name:john). This works for a quick check, but it collapses the moment you need complex logic. To build real, industry-standard search applications, you must learn to speak JSON to the cluster.
1. Introduction to the Query DSL Structure 🏗️
Definition: The Query DSL is a flexible, JSON-based language provided by Elasticsearch to define queries. It operates as an Abstract Syntax Tree (AST) consisting of two main types of clauses: leaf query clauses (searching for a specific value in a specific field) and compound query clauses (combining multiple queries).
The Problem: In traditional relational databases, you use SQL (SELECT * FROM table WHERE...). But Elasticsearch stores JSON documents, often deeply nested, and prioritizes "relevance scoring" over simple exact matches. SQL struggles to elegantly express concepts like "Find a document that mostly matches these words, but give it a higher score if this specific field matches exactly."
The Solution: A standardized JSON structure where every query is an object. This allows developers to programmatically build, nest, and scale queries without writing messy string concatenations.
Progressive Breakdown: How to read the DSL
Think of the Query DSL like building blocks.
- The Wrapper: Every search request payload starts with the
queryobject. - The Query Type: Inside the wrapper, you declare the specific type of query you want to run (e.g.,
match,term,bool). - The Target: Inside the query type, you specify the field and the value.
Example of the basic skeleton:
GET /products/_search
{
"query": { // 1. The Wrapper
"match": { // 2. The Query Type
"description": "laptop" // 3. The Target (Field: Value)
}
}
}In the industry, you will rarely see a single flat query like the one above. Real-world applications require combinations of queries, which brings us to the two fundamental ways to fetch data: exact matches and full-text searches.
2. Term-level Queries: Exact Matches and Filtering 🎯
Definition: Term-level queries are used to find exact, literal matches in the inverted index. They do not analyze or alter the search text you provide.
The Problem: Imagine you are querying a database for a user with the exact ID User-123X. If the search engine decides to be "smart" and breaks that string apart, lowercases it, or assumes you meant user 123, it might return the wrong user. When dealing with statuses, IDs, numbers, or tags, you need absolute, rigid exactness.
The Solution: The term query (and its sibling, the terms query).
How it works under the hood
When Elasticsearch ingests data, it usually runs it through an "analyzer" (more on that later). But for fields mapped as keyword, integer, boolean, or date, it stores the exact string in the inverted index. Term-level queries bypass the analyzer entirely. They look at the exact bytes you send and check if they exist in the index. What you see is exactly what it looks for.
Frequent Industry Usage
1. The term query (Single exact match):
Used heavily for enums, statuses, or boolean flags.
GET /orders/_search
{
"query": {
"term": {
"status.keyword": "SHIPPED"
}
}
}Note: Notice the .keyword suffix. In Elasticsearch, string fields are often mapped twice by default: once as text (for full-text search) and once as keyword (for exact matches).
2. The terms query (Multiple exact matches):
Equivalent to SQL's IN (...) clause.
GET /orders/_search
{
"query": {
"terms": {
"user_id": [101, 102, 103]
}
}
}3. The range query:
Essential for dates and numbers.
GET /orders/_search
{
"query": {
"range": {
"price": {
"gte": 50, // Greater than or equal to
"lte": 200 // Less than or equal to
}
}
}
}Funny Exaggeration: Using a full-text query instead of a term query to find a user ID is like putting up a "Wanted" poster for a bank robber that says, "Looking for a guy named John, or maybe Jonathan, or anyone who likes the name Jon." You will arrest half the city. Stick to term queries for exact identifiers.
3. Full-Text Queries: The Power of the Match Query 📖
Definition: Full-text queries are designed to search analyzed text fields. They process the user's search string using the same analyzer that was applied to the field during indexing.
The Problem: Humans are messy. They make typos, use synonyms, and mix up verb tenses. If a document contains the sentence "The quick foxes are jumping", and a user searches for "quick fox jumps", a rigid exact match will return zero results.
The Solution: The match query. It embraces the chaos of human language.
How it works under the hood
When you index a text field, Elasticsearch's analyzer strips punctuation, lowercases everything, and reduces words to their root forms (tokenization and stemming). "Jumping" becomes "jump".
When you use a match query, Elasticsearch does the exact same thing to the search string before querying the index.
Frequent Industry Usage
1. The match query (Standard full-text):
GET /articles/_search
{
"query": {
"match": {
"content": "quick fox jumps"
}
}
}2. The multi_match query (Searching across multiple fields):
In reality, you rarely search just one field. A user's search bar usually targets a title, a description, and tags all at once.
GET /articles/_search
{
"query": {
"multi_match": {
"query": "Elasticsearch guide",
"fields": ["title^3", "content", "tags"]
}
}
}Industry Standard Tip: Notice the ^3 on the title field. This is called "boosting." It tells Elasticsearch: "A match in the title is 3 times more important than a match in the content." This is how you tune relevance in production systems.
4. Filter Context vs. Query Context: Scoring Explained ⚖️
Definition:
- Query Context: Answers the question, "How well does this document match this query clause?" It calculates a relevance score (the
_scoremetadata field). - Filter Context: Answers the question, "Does this document match this query clause?" It is a strict Yes/No. No scores are calculated, and the results are automatically cached.
The Problem: Calculating relevance scores is mathematically expensive (CPU intensive). If you are looking for documents where is_active: true, calculating a score for "how true" it is makes no sense. It either is, or it isn't. If you run everything as a scoring query, your cluster will slow to a crawl under heavy load.
The Solution: The bool (Boolean) query. It allows you to split your query into strict rules (Filters) and scoring rules (Queries).
The Library Simulation
Imagine you are going to a massive public library (the server).
- Filter Context: You tell the librarian, "I only want books published in 2023, and they must be in the Sci-Fi section." The librarian instantly eliminates 99% of the building. This is binary. Yes or No.
- Query Context: Out of that specific pile, you say, "Now, sort them by how closely they talk about 'time travel paradoxes'." The librarian now has to read the summaries and grade (score) them.
The bool Query Structure
In the industry, the bool query is used for 95% of all searches. It has four main arrays:
must: The clause (query) must appear in matching documents. Contributes to score.should: The clause (query) should appear. If it does, the score goes up. (Like a "nice to have"). Contributes to score.filter: The clause (query) must appear. Does NOT contribute to score. Cached.must_not: The clause (query) must not appear. Does NOT contribute to score. Cached.
The Ultimate Production Example
Here is how you combine everything you just learned into a standard, production-grade query:
GET /products/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"description": "wireless headphones"
}
}
],
"should": [
{
"match": {
"brand": "Sony"
}
}
],
"filter": [
{
"term": {
"in_stock": true
}
},
{
"range": {
"price": {
"lte": 150
}
}
}
],
"must_not": [
{
"term": {
"condition.keyword": "refurbished"
}
}
]
}
}
}Why this is perfect:
- Filter & Must_Not: Elasticsearch first throws away all out-of-stock items, anything over $150, and anything refurbished. It caches this Yes/No result in memory. CPU usage is extremely low.
- Must: It takes the remaining small pool of documents and runs the heavy full-text
matchquery for "wireless headphones", calculating a score. - Should: If any of those remaining headphones happen to be the brand "Sony", it gives them a bonus point to push them to the top of the search results.
Golden Rule for Scale: If a query does not need to affect the search ranking (like filtering by date, user ID, or status), always put it in the filter clause. Your server's CPU will thank you.
References & Further Reading 📚
Challenge
You are tasked with building a complex search query for an e-commerce electronics store using Elasticsearch's Query DSL.
Construct a single bool query that finds products matching the following criteria. Assume the index is named products.
Mandatory Filters (for performance):
- The product's
category.keywordmust be exactly"Laptops". - The
pricemust be greater than or equal to1000and less than or equal to2000.
- The product's
Required Full-Text Search:
- The product must match the search phrase
"fast SSD". This search should run against thetitleanddescriptionfields. Give matches in thetitlefield 5 times more weight than matches in thedescriptionfield.
- The product must match the search phrase
Score Boosting:
- Products where the
brand.keywordis"InnovateBook"should be considered more relevant and receive a higher score, but this is not a strict requirement.
- Products where the
Exclusion:
- The query must exclude any documents where the
status.keywordis exactly"Refurbished".
- The query must exclude any documents where the
Your final query should be placed inside the query object.
Expected result
Your final JSON should be a complete Elasticsearch query.
The top-level query object should contain a single bool query.
Inside the bool query:
- The
filterclause should be an array containing two objects: atermquery forcategory.keyword: "Laptops"and arangequery for theprice. - The
mustclause should contain amulti_matchquery for"fast SSD"targeting thetitleanddescriptionfields, with a boost (^5) applied to thetitlefield. - The
shouldclause should contain atermquery to boost the score forbrand.keyword: "InnovateBook". - The
must_notclause should contain atermquery to exclude documents withstatus.keyword: "Refurbished".
This structure correctly separates non-scoring, absolute filters (for performance) from the scoring, relevance-based query clauses.