Full Combining Multiple Features
Let’s combine multiple features into a complex query.
Scenario: Finding Highly Rated, Affordable Products
We want to find products that are highly rated, affordable, from a specific brand, available within a certain distance, and added within the last month.
GET /products/_search
{
"query": {
"bool": {
"must": [
{ "match": { "description": "wireless headphones" } }
],
"filter": [
{ "term": { "brand": "BrandA" } },
{
"geo_distance": {
"distance": "10km",
"location": {
"lat": 40.7128,
"lon": -74.0060
}
}
},
{
"range": {
"date_added": {
"gte": "now-1M/M",
"lte": "now/M"
}
}
},
{
"range": {
"price": {
"lte": 100
}
}
}
],
"should": [
{
"nested": {
"path": "reviews",
"query": {
"bool": {
"must": [
{ "range": { "reviews.rating": { "gte": 4 } } }
]
}
}
}
}
],
"must_not": [
{ "term": { "color": "red" } }
]
}
},
"aggs": {
"avg_rating_by_brand": {
"terms": {
"field": "brand"
},
"aggs": {
"avg_rating": {
"avg": {
"field": "reviews.rating"
}
}
}
}
}
}
In this example:
- The must clause ensures the product description contains “wireless headphones“.
- The filter clause includes brand, geographic location, date range, and price filters.
- The should clause boosts products with high ratings.
- The must_not clause excludes red products.
- Aggregations are used to calculate the average rating by brand.
Using Query DSL For Complex Search Queries in Elasticsearch
Elasticsearch is a powerful search engine that provides a flexible and powerful query language called Query DSL (Domain Specific Language). Query DSL allows you to write complex search queries to retrieve the most relevant data from your Elasticsearch indices. This article will guide you through the basics and advanced features of Query DSL, with detailed examples and outputs, to help you master complex search queries in Elasticsearch.
Contact Us