Elasticsearch Query Examples: How to Perform Simple AND Queries
Use a bool query with must clauses to create AND logic in Elasticsearch, where every condition in the must array must match for a document to be returned.
The elastic/elasticsearch repository implements Boolean logic through the BoolQueryBuilder class, providing straightforward factory methods in QueryBuilders for constructing complex search criteria. Understanding these elasticsearch query examples helps developers build precise filters that require multiple conditions to be true simultaneously.
How Boolean Logic Works in Elasticsearch Query Examples
Elasticsearch constructs an AND query using the BoolQueryBuilder class located at server/src/main/java/org/elasticsearch/index/query/BoolQueryBuilder.java. This builder maintains a list called mustClauses that stores all sub-queries that must match.
When the query executes, the doToQuery method translates these clauses into a Lucene BooleanQuery. Each must clause is added with the BooleanClause.Occur.MUST flag, enforcing that all conditions must be satisfied for a document to be returned.
The public API exposes this functionality through QueryBuilders.boolQuery(), which returns a fresh BoolQueryBuilder instance. The must() method appends query builders to the internal mustClauses list.
Elasticsearch Query Examples: Java API Implementation
Use the QueryBuilders factory class to construct AND logic programmatically:
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryBuilder;
// Build an AND query matching documents where:
// field "status" is "active" AND field "age" is greater than 30
QueryBuilder andQuery = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("status", "active"))
.must(QueryBuilders.rangeQuery("age").gt(30));
Implementation details:
boolQuery()instantiatesBoolQueryBuilder(source:QueryBuilders.javalines 302-306)- Each
must()call executesmustClauses.add(queryBuilder)(source:BoolQueryBuilder.javalines 96-103) - During search execution,
doToQuerycreates the LuceneBooleanQuerywithOccur.MUSTfor each clause (source:BoolQueryBuilder.javalines 300-308)
Elasticsearch Query Examples: REST API JSON
The JSON DSL maps directly to the Java implementation:
GET /my_index/_search
{
"query": {
"bool": {
"must": [
{ "term": { "status": "active" } },
{ "range": { "age": { "gt": 30 } } }
]
}
}
}
The bool object corresponds to BoolQueryBuilder, while the must array populates the mustClauses list exactly as the Java must() method does.
Advanced Elasticsearch Query Examples: Combining AND, OR, and NOT
Complex logic combines must (AND), should (OR), and must_not (NOT) within a single bool query:
GET /my_index/_search
{
"query": {
"bool": {
"must": [
{ "term": { "status": "active" } }
],
"should": [
{ "match": { "city": "Paris" } },
{ "match": { "city": "Berlin" } }
],
"must_not": [
{ "term": { "role": "guest" } }
],
"minimum_should_match": 1
}
}
}
Only the must clauses enforce strict AND logic. The should clauses affect relevance scoring unless minimum_should_match is specified, while must_not excludes documents matching those conditions.
Key Source Files in the Elasticsearch Repository
Understanding the implementation requires examining these specific files in the elastic/elasticsearch repository:
-
server/src/main/java/org/elasticsearch/index/query/BoolQueryBuilder.java— Core implementation handlingmust,should,must_not, andfilterclauses, plus translation to LuceneBooleanQuery. -
server/src/main/java/org/elasticsearch/index/query/QueryBuilders.java— Factory class providing static methods includingboolQuery(),termQuery(), andrangeQuery(). -
server/src/test/java/org/elasticsearch/index/query/BoolQueryBuilderTests.java— Unit tests verifying correct behavior of must-clauses and overall bool query logic. -
server/src/main/java/org/elasticsearch/index/query/SearchExecutionContext.java— Provides the execution context where bool queries are transformed into executable Lucene queries.
Summary
- Use
boolwithmustto create AND logic in Elasticsearch, requiring all conditions to match. BoolQueryBuilderinBoolQueryBuilder.javamanages themustClauseslist and translates them to LuceneBooleanQuerywithOccur.MUST.- Factory methods in
QueryBuilders.javaprovide the entry point viaboolQuery()and specific query types liketermQuery()andrangeQuery(). - JSON DSL mirrors the Java API exactly, using
bool.mustarrays for AND operations. - Combine clauses using
must(AND),should(OR), andmust_not(NOT) for complex Boolean logic.
Frequently Asked Questions
What is the difference between must and filter in Elasticsearch queries?
must clauses contribute to the relevance score and enforce AND logic, meaning every condition must match. filter clauses also enforce AND logic and require all conditions to match, but they execute in filter context—skoring is ignored and results are cached for better performance. Use filter for exact matches and must when you need scoring based on relevance.
How do I perform an OR query instead of AND in Elasticsearch?
Use should clauses inside a bool query to achieve OR logic. Documents match if they satisfy at least one should clause. By default, if your bool query contains no must clauses, you need at least one should clause to match. You can adjust this threshold using the minimum_should_match parameter to require multiple optional conditions.
Can I nest bool queries inside other bool queries?
Yes, Elasticsearch supports arbitrarily deep nesting of bool queries. You can place a bool query inside the must, should, must_not, or filter clauses of another bool query. This allows complex Boolean logic such as (A AND B) OR (C AND D). The BoolQueryBuilder handles nested builders recursively through its doToQuery method.
What is the performance impact of using must clauses?
must clauses execute in query context, meaning they calculate relevance scores for each matching document. This requires more CPU resources than filter context operations. However, the performance impact is generally minimal for typical queries unless processing millions of documents with complex scoring. For better performance on exact-match conditions that don't affect scoring, move those clauses to filter instead of must.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →