Elasticsearch Faceted Search
Faceted search (filters + aggregations) helps users narrow results: filters by category, price range, rating.
Aggregations for Facets
GET /products/_search
{
"query": {
"match": { "name": "laptop" }
},
"aggs": {
"categories": {
"terms": {
"field": "category.keyword",
"size": 10
}
},
"price_ranges": {
"range": {
"field": "price",
"ranges": [
{ "to": 500 },
{ "from": 500, "to": 1000 },
{ "from": 1000, "to": 2000 },
{ "from": 2000 }
]
}
},
"brands": {
"terms": {
"field": "brand.keyword",
"size": 20
}
}
}
}
Response:
{
"aggregations": {
"categories": {
"buckets": [
{ "key": "electronics", "doc_count": 45 },
{ "key": "computers", "doc_count": 38 }
]
},
"price_ranges": {
"buckets": [
{ "to": 500, "doc_count": 12 },
{ "from": 500, "to": 1000, "doc_count": 28 }
]
}
}
}
Filter + Aggregation
GET /products/_search
{
"query": {
"bool": {
"must": [
{ "match": { "name": "laptop" } }
],
"filter": [
{ "term": { "category.keyword": "computers" } },
{ "range": { "price": { "gte": 500, "lte": 1500 } } }
]
}
},
"aggs": {
"brands": {
"terms": { "field": "brand.keyword", "size": 20 }
},
"ratings": {
"range": {
"field": "rating",
"ranges": [
{ "from": 4 }, // 4+ stars
{ "from": 3, "to": 4 } // 3-4 stars
]
}
}
},
"size": 20,
"from": 0
}







