Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(aggs): filter/filters aggs count what the same clause counts as a query (#1745) (#1752)

ordinary being51c1af384a3c
diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rs
index e0074bd11..a6f6d06b5 100644
--- a/engine/crates/xerj-engine/src/aggs.rs
+++ b/engine/crates/xerj-engine/src/aggs.rs
@@ -30,6 +30,8 @@
use std::collections::{HashMap, HashSet};
use serde_json::{json, Map, Value};
+use xerj_common::types::{FieldType, Schema};
+use xerj_query::ast::QueryNode;
// ─────────────────────────────────────────────────────────────────────────────
// Capability manifest — the single source of truth for "what aggregations exist"
@@ -178,6 +180,106 @@ pub fn run_aggs(aggs_def: &Value, docs: &[Value]) -> Value {
run_aggs_with_all(aggs_def, docs, docs)
}
+thread_local! {
+ /// Mapping/analyzer context for the `filter` and `filters` aggregations
+ /// (#1745), installed by [`run_aggs_with_schema`] for one synchronous
+ /// aggregation. `None` means no schema was supplied and those aggs fall
+ /// back to the legacy `_source`-only matcher.
+ ///
+ /// Scoped to the calling thread for the same reason as
+ /// `BUCKET_CAP_OVERRIDE`: the whole agg evaluator is synchronous and runs
+ /// on the caller's thread, so the value covers exactly the call it was
+ /// installed for and is invisible to a concurrent aggregation elsewhere.
+ static FILTER_SCHEMA: std::cell::RefCell<Option<Schema>> =
+ const { std::cell::RefCell::new(None) };
+}
+
+/// Restores the previous value on drop, so nested calls compose.
+struct FilterSchemaScope(Option<Schema>);
+
+impl FilterSchemaScope {
+ fn install(schema: Option<&Schema>) -> Self {
+ let previous =
+ FILTER_SCHEMA.with(|cell| std::mem::replace(&mut *cell.borrow_mut(), schema.cloned()));
+ Self(previous)
+ }
+}
+
+impl Drop for FilterSchemaScope {
+ fn drop(&mut self) {
+ FILTER_SCHEMA.with(|cell| *cell.borrow_mut() = self.0.take());
+ }
+}
+
+/// [`run_aggs_with_all`] with the index's mapping available to `filter` and
+/// `filters` aggregations (#1745).
+///
+/// Those two aggs evaluate their clauses per document. Without a schema they
+/// used `doc_matches_filter`'s `_source` approximation — `match` was a
+/// substring test, `match: "a b"` was AND rather than ES's default OR, and
+/// `match_phrase` ignored adjacency — so the same clause counted differently
+/// as an aggregation than as a query. With the schema in scope the clause is
+/// evaluated by `doc_matches_query_typed`, the matcher `_search`/`_count`
+/// use, so the two surfaces agree.
+pub fn run_aggs_with_schema(
+ aggs_def: &Value,
+ docs: &[Value],
+ all_docs: &[Value],
+ schema: &Schema,
+) -> Value {
+ let _scope = FilterSchemaScope::install(Some(schema));
+ run_aggs_with_all(aggs_def, docs, all_docs)
+}
+
+/// True when every field the clause targets is a declared `text` field.
+///
+/// Only then does `filter`/`filters` evaluate the clause with the query
+/// matcher; every other clause keeps `doc_matches_filter`. Two boundaries are
+/// deliberate:
+///
+/// * Keyword / numeric / boolean / date / ip clauses are already rewritten by
+/// the API layer's mapping-aware `match` → exact `term`/`terms` rewrite
+/// (`es_compat`), which is the form the legacy matcher answers correctly.
+/// Sending them through the query matcher tokenizes keyword values — the
+/// `filters_bucket.yml` `split_queries_on_whitespace` case counts 5 instead
+/// of ES's 4 that way.
+/// * Aggregation targets resolve field names with the agg-side rule
+/// (`get_nested_field` strips one suffix segment), while
+/// `doc_matches_query_typed` uses the recursive query-side rule. A suffix
+/// alias is not a declared field, so it stays on the agg-side matcher —
+/// `fast_aggs_multifield_suffix` pins that split.
+///
+/// `Bool` and the score wrappers recurse, so a clause that mixes a text leaf
+/// with an exact leaf stays on the legacy matcher rather than evaluating half
+/// of itself with each rule.
+fn clause_targets_only_text(node: &QueryNode, schema: &Schema) -> bool {
+ match node {
+ QueryNode::Match { field, .. }
+ | QueryNode::MatchPhrase { field, .. }
+ | QueryNode::MatchPhrasePrefix { field, .. }
+ | QueryNode::Term { field, .. }
+ | QueryNode::Terms { field, .. } => crate::index::declared_field(schema, field)
+ .is_some_and(|f| matches!(f.field_type, FieldType::Text)),
+ QueryNode::Bool {
+ must,
+ should,
+ must_not,
+ filter,
+ ..
+ } => must
+ .iter()
+ .chain(should)
+ .chain(must_not)
+ .chain(filter)
+ .all(|q| clause_targets_only_text(q, schema)),
+ QueryNode::Constant { query, .. }
+ | QueryNode::Boosted { query, .. }
+ | QueryNode::Named { query, .. } => clause_targets_only_text(query, schema),
+ QueryNode::Boosting { positive, .. } => clause_targets_only_text(positive, schema),
+ _ => false,
+ }
+}
+
// ── Aggregation bucket cap ────────────────────────────────────────────────────
//
// Hard cap on how many distinct buckets a single aggregation may materialise.
@@ -6766,14 +6868,33 @@ fn run_filter(
// terms lookups are already resolved to concrete arrays before the
// aggs run (es_compat `resolve_terms_lookups` walks the aggs subtree),
// so an unresolved lookup object is also correctly caught here.
- if let Err(e) = xerj_query::parser::parse_query(filter_query) {
- return json!({"error": format!("failed to parse `filter` aggregation query: {e}")});
- }
- let filtered_docs: Vec<Value> = docs
- .iter()
- .filter(|doc| doc_matches_filter(doc, filter_query))
- .cloned()
- .collect();
+ //
+ // #1745: the parsed AST is reused as the matcher when the index schema
+ // is in scope, so the bucket count and `_search`/`_count` for the same
+ // clause cannot disagree.
+ let parsed = match xerj_query::parser::parse_query(filter_query) {
+ Ok(node) => node,
+ Err(e) => {
+ return json!({"error": format!("failed to parse `filter` aggregation query: {e}")})
+ }
+ };
+ // #1745: only a clause whose targets are all declared text fields uses
+ // the query matcher (see `clause_targets_only_text`).
+ let use_schema = FILTER_SCHEMA.with(|cell| {
+ cell.borrow()
+ .as_ref()
+ .is_some_and(|s| clause_targets_only_text(&parsed, s))
+ });
+ let filtered_docs: Vec<Value> = FILTER_SCHEMA.with(|cell| {
+ let schema = cell.borrow();
+ docs.iter()
+ .filter(|doc| match (use_schema, schema.as_ref()) {
+ (true, Some(s)) => crate::index::doc_matches_query_typed(&parsed, doc, s),
+ _ => doc_matches_filter(doc, filter_query),
+ })
+ .cloned()
+ .collect()
+ });
let doc_count = sum_doc_count(&filtered_docs);
let mut result = serde_json::Map::new();
@@ -6818,21 +6939,62 @@ fn run_filters(
None => return json!({"buckets": {}}),
};
- // #959: same entry validation as `run_filter` — a clause the query
- // parser rejects must surface as an error, never as a bucket that
- // counts every document (the old catch-all behaviour). Applies to both
- // the named map and the anonymous array form.
- let clauses: Vec<&Value> = match filters_val {
- Value::Object(map) => map.values().collect(),
- Value::Array(arr) => arr.iter().collect(),
- _ => Vec::new(),
- };
- for q in clauses {
- if let Err(e) = xerj_query::parser::parse_query(q) {
- return json!({"error": format!("failed to parse `filters` aggregation query: {e}")});
+ // #959 (entry validation) and #1745 (one parse serves the rejection and
+ // the schema-aware matcher): reject a clause the query parser rejects
+ // instead of counting it, and keep the AST for the match below.
+ let mut named: Vec<(&String, &Value, QueryNode, bool)> = Vec::new();
+ let mut anonymous: Vec<(&Value, QueryNode, bool)> = Vec::new();
+ match filters_val {
+ Value::Object(map) => {
+ for (name, query) in map {
+ match xerj_query::parser::parse_query(query) {
+ Ok(node) => named.push((name, query, node, false)),
+ Err(e) => {
+ return json!({"error": format!("failed to parse `filters` aggregation query: {e}")})
+ }
+ }
+ }
+ }
+ Value::Array(arr) => {
+ for query in arr {
+ match xerj_query::parser::parse_query(query) {
+ Ok(node) => anonymous.push((query, node, false)),
+ Err(e) => {
+ return json!({"error": format!("failed to parse `filters` aggregation query: {e}")})
+ }
+ }
+ }
}
+ _ => {}
}
+ // Decide once per clause whether the query matcher applies.
+ FILTER_SCHEMA.with(|cell| {
+ if let Some(s) = cell.borrow().as_ref() {
+ for (_, _, node, flag) in named.iter_mut() {
+ *flag = clause_targets_only_text(node, s);
+ }
+ for (_, node, flag) in anonymous.iter_mut() {
+ *flag = clause_targets_only_text(node, s);
+ }
+ }
+ });
+
+ // #1745: with the index schema in scope, a text clause is evaluated by the
+ // same matcher `_search`/`_count` use, so a bucket's doc_count equals the
+ // count of the same clause as a query. Exact-field clauses keep the legacy
+ // `_source` matcher (see `clause_targets_only_text`), and without a schema
+ // (unit tests, the public `run_aggs*` entry points) everything does.
+ let clause_matches = |doc: &Value, raw: &Value, node: &QueryNode, use_schema: bool| -> bool {
+ if !use_schema {
+ return doc_matches_filter(doc, raw);
+ }
+ FILTER_SCHEMA.with(|cell| match cell.borrow().as_ref() {
+ Some(s) => crate::index::doc_matches_query_typed(node, doc, s),
+ None => doc_matches_filter(doc, raw),
+ })
+ };
+
// ES `keyed` defaults to true for a named `filters` map and false for
// an anonymous array. `keyed:false` on a named map rewrites to an
// array of buckets each carrying a `key` field.
@@ -6867,14 +7029,14 @@ fn run_filters(
match filters_val {
// Named filters: { "name1": { query }, "name2": { query } }
- Value::Object(map) => {
+ Value::Object(_) => {
let keyed = keyed_override.unwrap_or(true);
if keyed {
let mut buckets = serde_json::Map::new();
- for (name, query) in map {
+ for (name, query, node, use_schema) in &named {
let filtered: Vec<Value> = docs
.iter()
- .filter(|doc| doc_matches_filter(doc, query))
+ .filter(|doc| clause_matches(doc, query, node, *use_schema))
.cloned()
.collect();
let mut bucket = serde_json::Map::new();
@@ -6888,12 +7050,12 @@ fn run_filters(
}
}
}
- buckets.insert(name.clone(), Value::Object(bucket));
+ buckets.insert(name.to_string(), Value::Object(bucket));
}
if let Some(ok) = &other_key {
let other: Vec<Value> = docs
.iter()
- .filter(|d| !map.values().any(|q| doc_matches_filter(d, q)))
+ .filter(|d| !named.iter().any(|(_, q, n, u)| clause_matches(d, q, n, *u)))
.cloned()
.collect();
buckets.insert(ok.clone(), Value::Object(other_body(&other)));
@@ -6901,14 +7063,14 @@ fn run_filters(
json!({"buckets": buckets})
} else {
let mut buckets: Vec<Value> = Vec::new();
- for (name, query) in map {
+ for (name, query, node, use_schema) in &named {
let filtered: Vec<Value> = docs
.iter()
- .filter(|doc| doc_matches_filter(doc, query))
+ .filter(|doc| clause_matches(doc, query, node, *use_schema))
.cloned()
.collect();
let mut bucket = serde_json::Map::new();
- bucket.insert("key".to_string(), Value::String(name.clone()));
+ bucket.insert("key".to_string(), Value::String(name.to_string()));
bucket.insert("doc_count".to_string(), json!(sum_doc_count(&filtered)));
if let Some(sub) = sub_aggs {
let sr =
@@ -6924,7 +7086,7 @@ fn run_filters(
if let Some(ok) = &other_key {
let other: Vec<Value> = docs
.iter()
- .filter(|d| !map.values().any(|q| doc_matches_filter(d, q)))
+ .filter(|d| !named.iter().any(|(_, q, n, u)| clause_matches(d, q, n, *u)))
.cloned()
.collect();
let mut bucket = serde_json::Map::new();
@@ -6938,12 +7100,12 @@ fn run_filters(
}
}
// Anonymous filters: [ { query1 }, { query2 } ]
- Value::Array(arr) => {
+ Value::Array(_) => {
let mut buckets: Vec<Value> = Vec::new();
- for query in arr {
+ for (query, node, use_schema) in &anonymous {
let filtered: Vec<Value> = docs
.iter()
- .filter(|doc| doc_matches_filter(doc, query))
+ .filter(|doc| clause_matches(doc, query, node, *use_schema))
.cloned()
.collect();
let mut bucket = serde_json::Map::new();
@@ -6961,7 +7123,11 @@ fn run_filters(
if let Some(ok) = &other_key {
let other: Vec<Value> = docs
.iter()
- .filter(|d| !arr.iter().any(|q| doc_matches_filter(d, q)))
+ .filter(|d| {
+ !anonymous
+ .iter()
+ .any(|(q, n, u)| clause_matches(d, q, n, *u))
+ })
.cloned()
.collect();
let mut bucket = serde_json::Map::new();
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index f1f3c0d82..cb080febb 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -36,7 +36,7 @@ use xerj_vector::distance::DistanceMetric;
use xerj_vector::hnsw::{HnswIndex, HnswParams};
use xerj_vector::{Sq8CodeStore, Sq8Params};
-use crate::aggs::run_aggs_with_all;
+use crate::aggs::run_aggs_with_schema;
use crate::segment_cache_budget::{
CacheResident, SegmentCacheCategory, SegmentHydrationBudget, CATEGORY_COUNT,
};
@@ -15402,9 +15402,15 @@ impl Index {
candidates = scored.len(),
"knn served via HNSW (coverage gate passed)"
);
- let generated_companion_fields = {
+ let (generated_companion_fields, knn_schema) = {
let schema = self.schema.read().await;
- generated_embedding_companion_fields(&schema.schema)
+ (
+ generated_embedding_companion_fields(&schema.schema),
+ // #1745: filter/filters aggs evaluate their clauses with the
+ // query matcher; only clone the mapping when this request
+ // actually carries aggregations.
+ request.aggs.as_ref().map(|_| schema.schema.clone()),
+ )
};
Some(knn_result_from_scored(
self,
@@ -15414,6 +15420,7 @@ impl Index {
k,
started,
&generated_companion_fields,
+ knn_schema.as_ref(),
))
}
@@ -15692,9 +15699,15 @@ impl Index {
return None;
}
- let generated_companion_fields = {
+ let (generated_companion_fields, knn_schema) = {
let schema = self.schema.read().await;
- generated_embedding_companion_fields(&schema.schema)
+ (
+ generated_embedding_companion_fields(&schema.schema),
+ // #1745: filter/filters aggs evaluate their clauses with the
+ // query matcher; only clone the mapping when this request
+ // actually carries aggregations.
+ request.aggs.as_ref().map(|_| schema.schema.clone()),
+ )
};
Some(knn_result_from_scored(
self,
@@ -15704,6 +15717,7 @@ impl Index {
k,
started,
&generated_companion_fields,
+ knn_schema.as_ref(),
))
}
@@ -16577,9 +16591,15 @@ impl Index {
}
}
}
- let generated_companion_fields = {
+ let (generated_companion_fields, knn_schema) = {
let schema = self.schema.read().await;
- generated_embedding_companion_fields(&schema.schema)
+ (
+ generated_embedding_companion_fields(&schema.schema),
+ // #1745: filter/filters aggs evaluate their clauses with the
+ // query matcher; only clone the mapping when this request
+ // actually carries aggregations.
+ request.aggs.as_ref().map(|_| schema.schema.clone()),
+ )
};
// The default `_source` drops the generated embedding companions from
// every hit without reporting it (`apply_source_filter_measured`), and
@@ -16670,6 +16690,7 @@ impl Index {
ranked,
started,
&generated_companion_fields,
+ knn_schema.as_ref(),
);
result.timed_out = timed_out;
if timed_out {
@@ -16753,9 +16774,15 @@ impl Index {
// passage metadata. Child clauses retain ordinary ranking semantics;
// provenance is intentionally omitted until per-clause ownership is
// represented in the merged winner.
- let generated_companion_fields = {
+ let (generated_companion_fields, knn_schema) = {
let schema = self.schema.read().await;
- generated_embedding_companion_fields(&schema.schema)
+ (
+ generated_embedding_companion_fields(&schema.schema),
+ // #1745: filter/filters aggs evaluate their clauses with the
+ // query matcher; only clone the mapping when this request
+ // actually carries aggregations.
+ request.aggs.as_ref().map(|_| schema.schema.clone()),
+ )
};
let mut result = knn_result_from_scored(
self,
@@ -16765,6 +16792,7 @@ impl Index {
k_sum,
started,
&generated_companion_fields,
+ knn_schema.as_ref(),
);
result.timed_out = any_timed_out;
if any_timed_out {
@@ -25159,7 +25187,7 @@ impl Index {
} else {
&all_docs[..]
};
- run_aggs_with_all(aggs_def, fg, bg)
+ run_aggs_with_schema(aggs_def, fg, bg, &dmq_schema)
} else {
// Safety net: corpus not built — aggregate the hit window.
let sources: Vec<Value> = final_hits
@@ -25197,7 +25225,7 @@ impl Index {
} else {
&all_docs[..]
};
- run_aggs_with_all(aggs_def, &sources, bg)
+ run_aggs_with_schema(aggs_def, &sources, bg, &dmq_schema)
}
};
Some(agg_result)
@@ -40402,6 +40430,9 @@ fn apply_lexical_passages(hits: Vec<Hit>, query: &QueryNode) -> Vec<Hit> {
/// rank by score desc, cap the candidate pool at `k`, window with
/// `from`/`size`, and shape the response. Centralised so the exact and
/// approximate paths cannot drift on hits format or total semantics.
+// `schema` is the one parameter the aggregation tail needs beyond the kNN
+// executor's own tuple; a struct for it would exist only here.
+#[allow(clippy::too_many_arguments)]
fn knn_result_from_scored(
index: &Index,
request: &SearchRequest,
@@ -40410,6 +40441,7 @@ fn knn_result_from_scored(
k: usize,
started: std::time::Instant,
generated_companion_fields: &HashSet<String>,
+ schema: Option<&Schema>,
) -> SearchResult {
rank_knn_pool(&mut scored, k, |entry| entry.1);
knn_result_from_ranked(
@@ -40419,6 +40451,7 @@ fn knn_result_from_scored(
scored,
started,
generated_companion_fields,
+ schema,
)
}
@@ -40446,6 +40479,8 @@ fn rank_knn_pool<T>(pool: &mut Vec<T>, k: usize, score: impl Fn(&T) -> f32) {
/// Shape an already ranked, already `k`-capped pool (see [`rank_knn_pool`])
/// into the response.
+// Same parameter set as `knn_result_from_scored`, minus the ranking pool.
+#[allow(clippy::too_many_arguments)]
fn knn_result_from_ranked(
index: &Index,
request: &SearchRequest,
@@ -40453,6 +40488,7 @@ fn knn_result_from_ranked(
scored: Vec<(String, f32, Value, Option<u32>)>,
started: std::time::Instant,
generated_companion_fields: &HashSet<String>,
+ schema: Option<&Schema>,
) -> SearchResult {
// ES reports `hits.total.value` for a knn/semantic query as the size
// of the retrieved neighbor pool (min(k, matches)), NOT the number of
@@ -40475,7 +40511,13 @@ fn knn_result_from_ranked(
.iter()
.map(|(_, _, source, _)| source.clone())
.collect();
- crate::aggs::run_aggs(aggs_def, &sources)
+ // #1745: filter/filters aggs see the real mapping, so their clauses
+ // are evaluated by the query matcher instead of the `_source`
+ // approximation (`doc_matches_filter`).
+ match schema {
+ Some(s) => crate::aggs::run_aggs_with_schema(aggs_def, &sources, &sources, s),
+ None => crate::aggs::run_aggs(aggs_def, &sources),
+ }
});
let hits: Vec<Hit> = if request.size == 0 {
@@ -41600,7 +41642,7 @@ fn lookup_vector_quantization(schema: &Schema, field: &str) -> Option<String> {
/// `FieldConfig::fields` (object sub-paths and multi-fields). Returns `None`
/// for anything the schema does not declare — dynamic fields have no declared
/// mapping options to honour.
-fn declared_field<'a>(schema: &'a Schema, field: &str) -> Option<&'a FieldConfig> {
+pub(crate) fn declared_field<'a>(schema: &'a Schema, field: &str) -> Option<&'a FieldConfig> {
fn find<'a>(fields: &'a [FieldConfig], path: &[&str]) -> Option<&'a FieldConfig> {
let head = *path.first()?;
let tail = &path[1..];
@@ -45863,7 +45905,7 @@ pub(crate) fn value_present(v: &Value) -> bool {
}
}
-fn doc_matches_query_typed(q: &QueryNode, source: &Value, schema: &Schema) -> bool {
+pub(crate) fn doc_matches_query_typed(q: &QueryNode, source: &Value, schema: &Schema) -> bool {
match q {
QueryNode::MatchAll => true,
QueryNode::MatchNone => false,
diff --git a/engine/crates/xerj-engine/tests/aggs_filter_query_parity.rs b/engine/crates/xerj-engine/tests/aggs_filter_query_parity.rs
new file mode 100644
index 000000000..aeeb1195c
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/aggs_filter_query_parity.rs
@@ -0,0 +1,205 @@
+//! #1745: `filter` / `filters` aggregations must count exactly what the same
+//! clause counts as a query.
+//!
+//! Those aggs evaluate their clause per document through `doc_matches_filter`,
+//! a separate matcher over `_source` that had no mapping or analyzer: `match`
+//! was a lowercase `contains` per word (so `dog` matched "dogs"), a multi-word
+//! `match` required EVERY word (ES defaults to OR), and `match_phrase` never
+//! checked adjacency. The same five clauses counted as
+//! `m=3, t=0, or=0, phr=1` in an agg while `_count` answered
+//! `2, 0, 2, 0` (and ES 8.13 answers `2, 2, 2, 0`).
+//!
+//! The aggregation now runs with the index schema in scope, so
+//! `run_filter`/`run_filters` evaluate the parsed clause with
+//! `doc_matches_query_typed` — the matcher `_search`/`_count` use. This test
+//! pins parity clause-by-clause (the issue's actual invariant) plus the
+//! ES-pinned counts for the clauses where XERJ's query path already matches
+//! ES.
+//!
+//! `term` on a `text` field is deliberately asserted for PARITY only:
+//! XERJ's query path answers it by whole value (0 here) — a pre-existing
+//! contract this PR does not change — so the agg must join it rather than
+//! keep a second opinion. ES answers 2 by matching the analyzed token; that
+//! difference belongs to the query path, not to this aggregation fix.
+
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+use xerj_engine::{Engine, Index};
+use xerj_query::parse_request;
+
+fn make_engine(dir: &TempDir) -> Engine {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ Engine::new(config).expect("engine::new")
+}
+
+fn books_schema() -> Schema {
+ let mut schema = Schema::empty();
+ schema
+ .fields
+ .push(FieldConfig::new("title", FieldType::Text));
+ schema
+ .fields
+ .push(FieldConfig::new("kw", FieldType::Keyword));
+ schema
+}
+
+/// The issue's three documents, plus a keyword column so the exact-field
+/// control surface is covered too.
+async fn seed(engine: &Engine) -> std::sync::Arc<Index> {
+ engine.create_index("books", books_schema()).unwrap();
+ let idx = engine.get_index("books").unwrap();
+ for (id, title, kw) in [
+ ("1", "lazy dog sleeps", "alpha"),
+ ("2", "Quick dogs run", "beta"),
+ ("3", "the fox and the dog", "alpha"),
+ ] {
+ idx.index_document(Some(id.into()), json!({"title": title, "kw": kw}))
+ .await
+ .unwrap();
+ }
+ idx.refresh().await.unwrap();
+ idx
+}
+
+async fn count(idx: &Index, clause: &Value) -> u64 {
+ let req = parse_request(&json!({ "query": clause, "size": 0 })).expect("parse_request");
+ idx.search(&req).await.unwrap().total.value
+}
+
+async fn run_aggs(idx: &Index, aggs: Value) -> Value {
+ let req = parse_request(&json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": aggs,
+ }))
+ .expect("parse_request");
+ idx.search(&req)
+ .await
+ .unwrap()
+ .aggs
+ .expect("aggs in the response")
+}
+
+/// The issue's clauses, plus exact-field controls.
+fn clauses() -> Vec<(&'static str, Value)> {
+ vec![
+ ("match_dog", json!({"match": {"title": "dog"}})),
+ ("term_dog", json!({"term": {"title": "dog"}})),
+ ("match_or", json!({"match": {"title": "quick fox"}})),
+ (
+ "phrase_adjacent",
+ json!({"match_phrase": {"title": "fox and"}}),
+ ),
+ ("phrase_gap", json!({"match_phrase": {"title": "fox dog"}})),
+ ("term_kw", json!({"term": {"kw": "alpha"}})),
+ (
+ "bool_kw",
+ json!({"bool": {"should": [{"term": {"kw": "beta"}}], "minimum_should_match": 1}}),
+ ),
+ ]
+}
+
+#[tokio::test]
+async fn filter_and_filters_aggs_count_what_the_same_clause_counts_as_a_query() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let idx = seed(&engine).await;
+
+ for (name, clause) in clauses() {
+ let expected = count(&idx, &clause).await;
+ let body = run_aggs(
+ &idx,
+ json!({
+ "one": { "filter": clause },
+ "multi": { "filters": { "filters": { name: clause } } },
+ }),
+ )
+ .await;
+ assert_eq!(
+ body["one"]["doc_count"].as_u64(),
+ Some(expected),
+ "filter agg `{name}` must equal _count({clause}): {body}"
+ );
+ assert_eq!(
+ body["multi"]["buckets"][name]["doc_count"].as_u64(),
+ Some(expected),
+ "filters agg `{name}` must equal _count({clause}): {body}"
+ );
+ }
+
+ // ES-pinned counts for the clauses the query path itself already answers
+ // like ES 8.13 (`_count` was 2 / 2 / 0 before this change; only the agg
+ // disagreed).
+ let body = run_aggs(
+ &idx,
+ json!({
+ "m": { "filter": { "match": { "title": "dog" } } },
+ "t": { "filter": { "term": { "title": "dog" } } },
+ "or": { "filter": { "match": { "title": "quick fox" } } },
+ "phr": { "filter": { "match_phrase": { "title": "fox dog" } } },
+ "ok": { "filter": { "match_phrase": { "title": "fox and" } } },
+ }),
+ )
+ .await;
+ assert_eq!(body["m"]["doc_count"], json!(2), "match(dog) != ES: {body}");
+ assert_eq!(
+ body["or"]["doc_count"],
+ json!(2),
+ "match(quick fox) != ES: {body}"
+ );
+ assert_eq!(
+ body["phr"]["doc_count"],
+ json!(0),
+ "match_phrase(fox dog) != ES: {body}"
+ );
+ assert_eq!(
+ body["ok"]["doc_count"],
+ json!(1),
+ "match_phrase(fox and) != ES: {body}"
+ );
+ // Whole-value `term` on text: the query path's answer, not ES's (see the
+ // module comment). The point is that the agg no longer has its own answer.
+ assert_eq!(
+ body["t"]["doc_count"],
+ json!(0),
+ "term(dog) must match _count: {body}"
+ );
+}
+
+/// The schema scope must survive the bucket boundary: a `filter` nested under
+/// a `terms` bucket runs through `run_aggs_in_bucket`.
+#[tokio::test]
+async fn filter_aggs_inside_bucket_subaggs_use_the_same_matcher() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let idx = seed(&engine).await;
+
+ let body = run_aggs(
+ &idx,
+ json!({
+ "by_kw": {
+ "terms": { "field": "kw" },
+ "aggs": {
+ "dog": { "filter": { "match": { "title": "dog" } } },
+ "fox": { "filter": { "match": { "title": "quick fox" } } },
+ }
+ }
+ }),
+ )
+ .await;
+
+ let mut by_key = std::collections::HashMap::new();
+ for b in body["by_kw"]["buckets"].as_array().expect("buckets") {
+ by_key.insert(b["key"].as_str().unwrap().to_string(), b.clone());
+ }
+
+ // alpha: docs 1 ("lazy dog sleeps") and 3 ("the fox and the dog").
+ // beta: doc 2 ("Quick dogs run") — token `dogs`, not `dog`.
+ assert_eq!(by_key["alpha"]["dog"]["doc_count"], json!(2));
+ assert_eq!(by_key["alpha"]["fox"]["doc_count"], json!(1));
+ assert_eq!(by_key["beta"]["dog"]["doc_count"], json!(0));
+ assert_eq!(by_key["beta"]["fox"]["doc_count"], json!(1));
+}
diff --git a/engine/tests/es-compat-yaml/yaml/aggregations/filters_text_field_semantics.yml b/engine/tests/es-compat-yaml/yaml/aggregations/filters_text_field_semantics.yml
new file mode 100644
index 000000000..968e47b32
--- /dev/null
+++ b/engine/tests/es-compat-yaml/yaml/aggregations/filters_text_field_semantics.yml
@@ -0,0 +1,71 @@
+setup:
+ - do:
+ indices.create:
+ index: books
+ body:
+ mappings:
+ properties:
+ title:
+ type: text
+ - do:
+ bulk:
+ refresh: true
+ body:
+ - index:
+ _index: books
+ _id: "1"
+ - title: lazy dog sleeps
+ - index:
+ _index: books
+ _id: "2"
+ - title: Quick dogs run
+ - index:
+ _index: books
+ _id: "3"
+ - title: the fox and the dog
+
+---
+"filter and filters aggregations count the same clause as the query (#1745)":
+
+ - do:
+ search:
+ index: books
+ body:
+ size: 0
+ aggs:
+ single:
+ filter:
+ match:
+ title: dog
+ multi:
+ filters:
+ filters:
+ dog:
+ match:
+ title: dog
+ - match: { hits.total.value: 3 }
+ - match: { aggregations.single.doc_count: 2 }
+ - match: { aggregations.multi.buckets.dog.doc_count: 2 }
+
+ # `match` defaults to OR; `match_phrase` requires adjacency.
+ - do:
+ search:
+ index: books
+ body:
+ size: 0
+ aggs:
+ or_query:
+ filter:
+ match:
+ title: quick fox
+ phrase_gap:
+ filter:
+ match_phrase:
+ title: fox dog
+ phrase_adjacent:
+ filter:
+ match_phrase:
+ title: fox and
+ - match: { aggregations.or_query.doc_count: 2 }
+ - match: { aggregations.phrase_gap.doc_count: 0 }
+ - match: { aggregations.phrase_adjacent.doc_count: 1 }