For AI agents: this page is also available as Markdown at /docs/facets-and-aggregations.md. Every docs page is: add .md to its URL. llms.txt lists them all.

Facets and aggregations

Facets group the documents a query matches into buckets and count them: "Science fiction (31)", "Under $20 (18)", "May (240)". Metrics reduce them to numbers: average price, highest latency. Both cover every matching document, not just the page of hits, and they come back in the same response as the hits, computed from the same consistent view of the collection. Counts are exact.

In the WarpSearch API they are the facets and metrics objects of a search request, and they work the same with any query language. You can also write them as Elasticsearch aggs or Solr facets (through the es and solr languages or the compatible endpoints), as SQL GROUP BY, or as LogQL metric queries. All of these produce the same kinds of buckets; see Other languages.

Facets in a request

Add a facets object to any search request. Each key is a name you choose, and it comes back unchanged in the response.

curl -X POST https://api.warpsearch.io/v1/search/books \
  -H "Authorization: Bearer $WARPSEARCH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "lucene",
    "query": "title:dune",
    "limit": 5,
    "facets": {
      "by_genre": {"type": "terms", "field": "genre", "size": 10,
                   "metrics": {"avg_price": "avg(price)"},
                   "order": {"by": "avg_price", "desc": true}},
      "per_decade": {"type": "range", "field": "year", "start": 1900, "end": 2030, "interval": 10},
      "price_tiers": {"type": "query",
                      "buckets": {"cheap": "price:<10", "pricey": "price:>=10"}}
    },
    "metrics": {"max_price": "max(price)"}
  }'
{
  "total": 42,
  "hits": [],
  "facets": {
    "by_genre": {
      "type": "terms",
      "field": "genre",
      "missing": 2,
      "buckets": [
        {"value": "scifi", "count": 31, "metrics": {"avg_price": 11.7}},
        {"value": "classic", "count": 9, "metrics": {"avg_price": 8.2}}
      ]
    }
  },
  "metrics": {"max_price": 24.5}
}

The same analytics as Elasticsearch aggs, answered in Elasticsearch's aggregation shape. A fixed-width range facet is a histogram, and query buckets are a filters aggregation:

curl -X POST https://api.warpsearch.io/compat/es/books/_search \
  -H "Authorization: Bearer $WARPSEARCH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": {"match": {"title": "dune"}},
    "size": 5,
    "aggs": {
      "by_genre": {"terms": {"field": "genre", "size": 10, "order": {"avg_price": "desc"}},
                   "aggs": {"avg_price": {"avg": {"field": "price"}}}},
      "per_decade": {"histogram": {"field": "year", "interval": 10}},
      "price_tiers": {"filters": {"filters": {
        "cheap": {"range": {"price": {"lt": 10}}},
        "pricey": {"range": {"price": {"gte": 10}}}}}},
      "max_price": {"max": {"field": "price"}}
    }
  }'

The same body works on /compat/opensearch/books/_search.

The same analytics with the JSON Facet API, answered in Solr's facet shape:

curl "https://api.warpsearch.io/compat/solr/books/select" \
  -H "Authorization: Bearer $WARPSEARCH_API_KEY" \
  --data-urlencode "q=title:dune" \
  --data-urlencode "rows=5" \
  --data-urlencode 'json.facet={
    "by_genre": {"type": "terms", "field": "genre", "limit": 10, "sort": "avg_price desc",
                 "facet": {"avg_price": "avg(price)"}},
    "per_decade": {"type": "range", "field": "year", "start": 1900, "end": 2030, "gap": 10},
    "cheap": {"type": "query", "q": "price:[* TO 10}"},
    "max_price": "max(price)"}'

Hits arrive as usual, so a results page and its sidebar take one request. Set limit to 0 when you only want the analytics.

Facet types

type Groups by Main options
terms Each distinct value of a field. size (number of buckets), min_count, missing (also count documents with no value), order
range (or histogram) Fixed-width numeric buckets. field, interval (required), start, end
date_histogram Time buckets. interval (a number, a duration such as 5m, or auto) or calendar_interval (day, week, month, quarter, year), time_zone, format
query Named buckets that you define with queries. buckets: a map of bucket name to query

To count matches by distance from a point or by area, use a query facet with one geo query per bucket. For map grids and distance rings, use the geo facet types (geohash_grid, geotile_grid, geohex_grid, geo_distance) and the geo_bounds and geo_centroid metrics; see Geo aggregations.

Every facet also accepts metrics and facets, which run once per bucket. For example, to get the average price and the top publishers of every category in one request, give a terms facet a metrics object and a nested facets object:

"by_category": {
  "type": "terms", "field": "category", "size": 10,
  "metrics": {"avg_price": "avg(price)"},
  "facets": {"publishers": {"type": "terms", "field": "publisher", "size": 5}}
}

Notes on terms:

Each bucket in the response has a value and a count, plus metrics and facets when you asked for them. A range or date_histogram bucket also has from and to (the lower bound is included, the upper one is not), and a date bucket has key_as_string, the formatted lower bound.

Metrics

A metric is "function(field)" or an object. Put it at the top of the request for one number over all matches, or inside a facet for one number per bucket.

Function Result Notes
avg, sum, min, max A number Missing values are skipped. An empty set returns null. On a multi-valued field, every value counts: avg is the mean of all values.
count A number Values: on a single-valued field, the documents with a value.
stats {count, min, max, avg, sum}
cardinality A number ({value} in Elasticsearch shape) Approximate distinct count. Exact up to a threshold, then about 1.6% error. Not on text fields.
percentiles A map keyed by percent, such as "99.0" Approximate, from a t-digest. Numeric and date fields. Multi-valued inputs may contribute each document’s average rather than every individual value. Use one value per document when this distinction matters.
percentile_ranks A map keyed by value Approximate. Needs values. Multi-valued fields as for percentiles.
median_absolute_deviation A number Approximate, derived from a t-digest; available where this aggregation is enabled.

The string form uses default parameters. To set them for the three approximate functions, use the object form:

"metrics": {
  "p": {"func": "percentiles", "field": "latency_ms", "percents": [50, 99], "keyed": false},
  "users": {"func": "cardinality", "field": "user_id", "precision_threshold": 1000},
  "slow": {"func": "percentile_ranks", "field": "latency_ms", "values": [500]}
}

precision_threshold is capped at 40000. percents default to 1, 5, 25, 50, 75, 95 and 99. compression (20 to 1000) tunes accuracy. Metric names are free-form strings and come back unchanged.

Status by API: cardinality, percentiles and percentile_ranks are available through the /v1 metrics object and through Elasticsearch and OpenSearch aggregations. stats and the basic functions work everywhere.

Date histograms

"facets": {
  "per_day": {"type": "date_histogram", "field": "published",
              "calendar_interval": "day", "time_zone": "America/Denver"}
}

Calendar intervals follow the civil calendar: months vary in length and a daylight-saving day has 23 or 25 hours. Fixed intervals such as 5m or 1h are exact durations.

By default the histogram runs from the first non-empty bucket to the last, with empty buckets between. To widen it, set extended_start and extended_end, and trim_empty to drop empty edge buckets outside them. offset shifts the bucket boundaries, in milliseconds for dates. Explicit bounds, for example from a date range in the query or time_range, save the engine a pass to find them.

A histogram returns at most 5000 buckets, or 1024 when it has metrics or nested facets. A wider span fails with limit_exceeded; use a bigger interval or a narrower range.

Faceted navigation

In a sidebar where users tick several values, each facet should still show the alternatives to what was ticked, so count each facet without its own selection. In the WarpSearch request, put the user's choices in post_filters: they narrow the hits and leave facets and metrics untouched.

{
  "language": "lucene",
  "query": "title:dune",
  "post_filters": ["genre:scifi"],
  "facets": {"by_genre": {"type": "terms", "field": "genre", "size": 10}}
}

post_filters apply to every facet in the request. When the user has selected values in several facets and each facet should drop only its own selection, put the other facets' selections in filters and send one request per facet, or use Solr's tags below.

Put the choices in post_filter, which narrows the hits and leaves the aggregations untouched:

{
  "query": {"match": {"title": "dune"}},
  "post_filter": {"term": {"genre": "scifi"}},
  "aggs": {"by_genre": {"terms": {"field": "genre", "size": 10}}}
}

Tag the filter query and exclude it in the facet, so each facet ignores only its own selection:

q=title:dune&fq={!tag=g}genre:scifi&facet=true&facet.field={!ex=g}genre

Other languages

You write You get
Elasticsearch aggs: terms, histogram, date_histogram, range, date_range, filters, filter, global, top_hits, and the metrics avg, sum, min, max, value_count, stats, extended_stats, cardinality, percentiles, percentile_ranks The same buckets, in Elasticsearch shape.
Solr facet.field, facet.range, facet.query, facet.pivot, stats, and the JSON Facet API Solr-shaped facet results.
SQL GROUP BY a, b, COUNT(*), AVG, SUM, MIN, MAX, HAVING COUNT(*) >= n, SELECT DISTINCT col Nested terms facets.
LogQL count_over_time, sum by (...), avg_over_time A date histogram per series.

Elasticsearch terms supports include and exclude, subject to field-type restrictions. Composite, multi-term and rare/significant-term aggregations have additional availability and input limits; sampling aggregations are unsupported. See Elasticsearch aggregations. Supported pipeline aggregations run over returned buckets. General scripts, ordering by sketch metrics and hdr percentiles remain unsupported; read response warnings for approximations.

Plan limits and cost

Your plan caps how many facets a request may carry and how many buckets each returns, in addition to the fixed histogram limits above. A size of -1 is capped at your plan's limit rather than unbounded. Facets over a high-cardinality field with nested facets are the most expensive shape, so filter first and keep size small, and bound date histograms with a time range; see Pricing.

View this page as Markdown

Cookie settings

Optional tracking stays off until you choose it. Your choice applies to this browser for 180 days. Read the details.

Essential storage keeps you signed in, protects forms, and remembers this choice. It is always available.