Elasticsearch Query Guide
Bool Query Structure
POST /products/_search
{
"query": {
"bool": {
"must": [
{ "match": { "name": "laptop" } } // scored — affects _score
],
"filter": [
{ "term": { "status": "available" } }, // not scored — cached
{ "range": { "price": { "gte": 500, "lte": 2000 } } }
],
"should": [
{ "match": { "brand": "dell" } }, // boosts score if matched
{ "match": { "tags": "gaming" } }
],
"minimum_should_match": 1,
"must_not": [
{ "term": { "discontinued": true } }
]
}
},
"sort": [
{ "_score": "desc" },
{ "price": "asc" }
],
"from": 0, "size": 20,
"_source": ["name", "price", "brand"]
}
Common Query Types
| Query | Use Case | Example |
|---|---|---|
| match | Full-text on analyzed field | {"match":{"title":"quick brown"}} |
| match_phrase | Exact phrase in order | {"match_phrase":{"body":"quick brown fox"}} |
| multi_match | Search multiple fields | {"multi_match":{"query":"go","fields":["title^2","body"]}} |
| term | Exact value (keyword, id) | {"term":{"status":"active"}} |
| terms | Exact value from list | {"terms":{"status":["active","pending"]}} |
| range | Numeric/date range | {"range":{"date":{"gte":"2024-01-01"}}} |
| exists | Field has a value | {"exists":{"field":"email"}} |
| fuzzy | Typo tolerance | {"fuzzy":{"name":{"value":"lapto","fuzziness":"AUTO"}}} |
| wildcard | Wildcard pattern (slow) | {"wildcard":{"email":"*@gmail.com"}} |
| nested | Query inside nested objects | {"nested":{"path":"comments","query":{...}}} |
Aggregations
POST /orders/_search
{
"size": 0,
"aggs": {
"by_status": {
"terms": { "field": "status", "size": 10 }
},
"revenue_by_month": {
"date_histogram": {
"field": "created_at",
"calendar_interval": "month"
},
"aggs": {
"total_revenue": { "sum": { "field": "amount" } },
"avg_order": { "avg": { "field": "amount" } }
}
},
"price_percentiles": {
"percentiles": { "field": "amount", "percents": [50, 95, 99] }
},
"stats": { "extended_stats": { "field": "amount" } }
}
}