Skip to content

Aggregations and ES|QL

The same question asked two ways: how many products each category has, and their average price. Both run on any license.

Cargo.toml
[dependencies]
oxsearch = { version = "0.2", features = ["admin", "aggs", "esql", "transport-reqwest"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt"] }
crates/oxsearch/examples/analytics.rs
// Products by category, with each category's average price: a terms
// aggregation with an average under it, sent with `typed_keys` so the
// results read back typed.
let request = search::Request::new().index(INDEX).typed_keys(true).body(
search::RequestBody::new()
.size(0)
.aggregations(Aggs::new().add(
"by_category",
Agg::terms("category", 10).sub("avg_price", Agg::avg("price")),
)),
);
let response: search::Response<Value, Aggregates> = client.send_as(&request).await?;
let results = response.0.aggregations.expect("aggregation results");
let averages = results
.string_terms("by_category")
.into_iter()
.map(|bucket| bucket.aggregations.value("avg_price").unwrap_or_default());
for ((category, count), average) in results.terms("by_category").into_iter().zip(averages) {
println!("{category}: {count} products, {average:.2} on average");
}

Agg builds the common bucket, metric and pipeline aggregations, .sub() nests one under another, and Aggs names them for the request. Sent with typed_keys, the results read back as Aggregates, and Results picks them out by name: value, stats, terms, histogram, date_histogram, ranges, filters, percentiles, top_hits, and the same in each bucket’s own sub-aggregations.

Every aggregation the specification describes is a generated type, for those the builders don’t cover; Agg::of takes any of them.

crates/oxsearch/examples/analytics.rs
// The same question in ES|QL. Values go as parameters, never into the
// query's text, and the rows read into `Category` by column name.
let rows: Vec<Category> = Esql::from_index(INDEX)
.where_(col("price").gte(5.0))
.stats(
[("products", "COUNT(*)"), ("average", "AVG(price)")],
["category"],
)
.sort([col("products").desc(), col("category").asc()])
.fetch(&client)
.await?;
for row in &rows {
println!(
"{}: {} products, {:.2} on average",
row.category, row.products, row.average
);
}
crates/oxsearch/examples/analytics.rs
/// A row of the ES|QL query's results, read by column name.
#[derive(Debug, Deserialize)]
struct Category {
category: String,
products: i64,
average: f64,
}

Esql builds the query: FROM, WHERE, EVAL, KEEP, DROP, RENAME, SORT, LIMIT, STATS … BY, MV_EXPAND, FORK and FUSE. Values are sent as parameters, never written into the query’s text, and identifiers are quoted.

fetch reads each row into your own type by column name. A dotted column, such as author.name, fills a nested struct, and a column missing or of the wrong type fails with Error::Row, which names the row and the column. With the esql-arrow feature, fetch_arrow reads the results as Arrow record batches instead.