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

QueryUse CaseExample
matchFull-text on analyzed field{"match":{"title":"quick brown"}}
match_phraseExact phrase in order{"match_phrase":{"body":"quick brown fox"}}
multi_matchSearch multiple fields{"multi_match":{"query":"go","fields":["title^2","body"]}}
termExact value (keyword, id){"term":{"status":"active"}}
termsExact value from list{"terms":{"status":["active","pending"]}}
rangeNumeric/date range{"range":{"date":{"gte":"2024-01-01"}}}
existsField has a value{"exists":{"field":"email"}}
fuzzyTypo tolerance{"fuzzy":{"name":{"value":"lapto","fuzziness":"AUTO"}}}
wildcardWildcard pattern (slow){"wildcard":{"email":"*@gmail.com"}}
nestedQuery 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" } } } }