Skip to Content
Elasticsearch: The Definitive Guide
book

Elasticsearch: The Definitive Guide

by Clinton Gormley, Zachary Tong
January 2015
Intermediate to advanced content levelIntermediate to advanced
724 pages
13h 21m
English
O'Reilly Media, Inc.
Content preview from Elasticsearch: The Definitive Guide

Chapter 30. Filtering Queries and Aggregations

A natural extension to aggregation scoping is filtering. Because the aggregation operates in the context of the query scope, any filter applied to the query will also apply to the aggregation.

Filtered Query

If we want to find all cars over $10,000 and also calculate the average price for those cars, we can simply use a filtered query:

GET /cars/transactions/_search?search_type=count
{
    "query" : {
        "filtered": {
            "filter": {
                "range": {
                    "price": {
                        "gte": 10000
                    }
                }
            }
        }
    },
    "aggs" : {
        "single_avg_price": {
            "avg" : { "field" : "price" }
        }
    }
}

Fundamentally, using a filtered query is no different from using a match query, as we discussed in the previous chapter. The query (which happens to include a filter) returns a certain subset of documents, and the aggregation operates on those documents.

Filter Bucket

But what if you would like to filter just the aggregation results? Imagine we are building the search page for our car dealership. We want to display search results according to what the user searches for. But we also want to enrich the page by including the average price of cars (matching the search) that were sold in the last month.

We can’t use simple scoping here, since there are two different criteria. The search results must match ford, but the aggregation results must match ford AND sold > now - 1M.

To solve this problem, we can use a special bucket called filter. You specify a filter, and when documents match the filter’s criteria, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Elasticsearch in Action

Elasticsearch in Action

Roy Russo, Matthew Lee Hinman, Radu Gheorghe
MongoDB: The Definitive Guide, 3rd Edition

MongoDB: The Definitive Guide, 3rd Edition

Shannon Bradshaw, Eoin Brazil, Kristina Chodorow

Publisher Resources

ISBN: 9781449358532Errata