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(knn): thread filter+boost through top-level kNN, honor similarity cutoff, accept knn:[...] arrays

xerj-org0c83140926a6
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index ad0ef786b..5b41104f4 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -4803,50 +4803,141 @@ pub async fn search(
// profile builder still needs to know whether this was a knn search.
let original_knn: Option<Value> = body.knn.clone();
+ // Normalise the top-level `knn` spec. ES accepts an object OR an array
+ // of clauses; the array form used to fall through every `.get(...)` in
+ // this block (arrays have no keys) and silently return ZERO hits. A
+ // single-element array is exactly the object form; a multi-element
+ // array is the ES multi-kNN search (per-clause top-k, summed scores).
+ let knn_norm: Option<Value> = match body.knn.clone() {
+ Some(Value::Array(arr)) if arr.is_empty() => {
+ let reason = "[knn] must not be empty";
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(json!({
+ "error": {
+ "root_cause": [{ "type": "illegal_argument_exception", "reason": reason }],
+ "type": "illegal_argument_exception",
+ "reason": reason,
+ },
+ "status": 400,
+ })),
+ )
+ .into_response();
+ }
+ Some(Value::Array(arr)) if arr.len() == 1 => Some(arr.into_iter().next().unwrap()),
+ other => other,
+ };
+
+ // Per-clause effective k (explicit `k`, else `num_candidates`, else 10 —
+ // the same derivation the query parser applies).
+ fn knn_clause_k(knn_val: &Value) -> usize {
+ let num_candidates = knn_val
+ .get("num_candidates")
+ .and_then(Value::as_u64)
+ .map(|n| n as usize);
+ knn_val
+ .get("k")
+ .and_then(Value::as_u64)
+ .map(|n| n as usize)
+ .or(num_candidates)
+ .unwrap_or(10)
+ }
+
+ // Pass the ES knn spec through to the query DSL `knn` node VERBATIM —
+ // field, query_vector, k, num_candidates, filter (object or array),
+ // boost, and similarity all reach the parser. The old path round-tripped
+ // through a lossy QueryNode builder that DROPPED `filter` (unfiltered
+ // results ranked above filtered ones), `similarity` (sub-threshold docs
+ // returned), and `boost`.
+ fn knn_spec_to_query_json(knn_val: &Value) -> Value {
+ let mut knn = serde_json::Map::new();
+ for key in [
+ "field",
+ "query_vector",
+ "k",
+ "num_candidates",
+ "filter",
+ "boost",
+ "similarity",
+ ] {
+ if let Some(v) = knn_val.get(key) {
+ knn.insert(key.to_string(), v.clone());
+ }
+ }
+ json!({ "knn": knn })
+ }
+
// ES knn semantics: a pure (non-hybrid) `knn` search returns at most `k`
- // nearest neighbours, further bounded by the request `size`, and reports
- // `hits.total` as the number of candidates actually returned — NOT the
- // brute-force match count over the whole index. Capture that cap here,
- // before the knn query is folded into a `bool` and `body.size` is bumped.
+ // nearest neighbours (summed across clauses for the array form), further
+ // bounded by the request `size`, and reports `hits.total` as the number
+ // of candidates actually returned — NOT the brute-force match count over
+ // the whole index. Capture that cap here, before the knn query is folded
+ // into a `bool` and `body.size` is bumped.
// Hybrid knn (knn + a sibling `query`) keeps normal scoring/counting.
let knn_total_cap: Option<usize> =
- body.knn
+ knn_norm
.as_ref()
.filter(|_| body.query.is_none())
.map(|knn_val| {
- let num_candidates = knn_val
- .get("num_candidates")
- .and_then(Value::as_u64)
- .map(|n| n as usize);
- let k = knn_val
- .get("k")
- .and_then(Value::as_u64)
- .map(|n| n as usize)
- .or(num_candidates)
- .unwrap_or(10);
- k.min(body.size)
+ let k_total = match knn_val {
+ Value::Array(arr) => arr
+ .iter()
+ .fold(0usize, |acc, c| acc.saturating_add(knn_clause_k(c))),
+ single => knn_clause_k(single),
+ };
+ k_total.min(body.size)
});
- // If top-level "knn" is present, synthesise a Knn query and merge with any "query".
- let effective_body: EsSearchBody = if let Some(ref knn_val) = body.knn {
- let knn_query = knn_body_to_query_node(knn_val);
+ // If top-level "knn" is present, synthesise knn query node(s) and merge
+ // with any "query".
+ let effective_body: EsSearchBody = if let Some(ref knn_val) = knn_norm {
+ let (knn_query_json, k_total) = match knn_val {
+ Value::Array(arr) => {
+ if body.query.is_some() {
+ // Multiple knn clauses + a sibling `query` need ES's
+ // full score-union executor; XERJ does not implement
+ // that combination. Fail loud instead of silently
+ // dropping the knn contributions.
+ let reason = "multiple [knn] clauses combined with a [query] are not \
+ supported by this XERJ version; run the knn array \
+ without [query], or a single knn clause with [query]";
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(json!({
+ "error": {
+ "root_cause": [{ "type": "illegal_argument_exception", "reason": reason }],
+ "type": "illegal_argument_exception",
+ "reason": reason,
+ },
+ "status": 400,
+ })),
+ )
+ .into_response();
+ }
+ let clauses: Vec<Value> = arr.iter().map(knn_spec_to_query_json).collect();
+ let k_total = arr
+ .iter()
+ .fold(0usize, |acc, c| acc.saturating_add(knn_clause_k(c)));
+ (json!({ "bool": { "should": clauses } }), k_total)
+ }
+ single => (knn_spec_to_query_json(single), knn_clause_k(single)),
+ };
let merged_query = if let Some(ref existing_q) = body.query {
// Hybrid: combine knn + query as a bool should.
json!({
"bool": {
"should": [
existing_q,
- knn_query_node_to_json(&knn_query)
+ knn_query_json
]
}
})
} else {
- knn_query_node_to_json(&knn_query)
+ knn_query_json
};
- let k = knn_val.get("k").and_then(Value::as_u64).unwrap_or(10) as usize;
EsSearchBody {
query: Some(merged_query),
- size: body.size.max(k),
+ size: body.size.max(k_total),
knn: None,
..body.clone()
}
@@ -21603,74 +21694,6 @@ pub(crate) fn get_source_value_by_path(source: &Value, path: &str) -> Option<Val
walk(source, &segs)
}
-/// Parse the ES 8.x top-level `knn` spec into a `QueryNode::Knn`.
-///
-/// `k` defaults to `num_candidates` when unset (ES accepts either in
-/// some contexts — e.g. `knn: { num_candidates: 1 }` means retrieve 1
-/// candidate and return 1), otherwise defaults to 10.
-fn knn_body_to_query_node(knn_val: &Value) -> xerj_query::ast::QueryNode {
- let field = knn_val
- .get("field")
- .and_then(Value::as_str)
- .unwrap_or("embedding")
- .to_string();
- let vector: Vec<f32> = knn_val
- .get("query_vector")
- .and_then(Value::as_array)
- .map(|arr| {
- arr.iter()
- .filter_map(|v| v.as_f64().map(|f| f as f32))
- .collect()
- })
- .unwrap_or_default();
- let num_candidates = knn_val
- .get("num_candidates")
- .and_then(Value::as_u64)
- .map(|n| n as usize);
- let k = knn_val
- .get("k")
- .and_then(Value::as_u64)
- .map(|n| n as usize)
- .or(num_candidates)
- .unwrap_or(10);
- let boost = knn_val
- .get("boost")
- .and_then(Value::as_f64)
- .map(|f| f as f32);
- xerj_query::ast::QueryNode::Knn {
- field,
- vector,
- k,
- num_candidates,
- filter: None,
- boost,
- }
-}
-
-/// Serialise a `QueryNode` to a `Value` for embedding into a bool query.
-fn knn_query_node_to_json(node: &xerj_query::ast::QueryNode) -> Value {
- if let xerj_query::ast::QueryNode::Knn {
- field,
- vector,
- k,
- num_candidates,
- ..
- } = node
- {
- let mut knn = json!({
- "field": field,
- "query_vector": vector,
- "k": k
- });
- if let Some(nc) = num_candidates {
- knn["num_candidates"] = json!(nc);
- }
- json!({ "knn": knn })
- } else {
- serde_json::to_value(node).unwrap_or(json!({"match_all": {}}))
- }
-}
-
/// Build inner_hits for a nested query.
///
/// For now we return the full document source as a single inner hit per nested field.
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index e6433cfc7..3e61a1a7a 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -3919,6 +3919,7 @@ impl Index {
/// behaviour (BBQ disk quantisation, IVF clustering) are not
/// necessary for wire-correctness on these tests because the
/// expected doc order is deterministic given exact scoring.
+ #[allow(clippy::too_many_arguments)]
pub async fn run_knn_brute_force(
&self,
request: &SearchRequest,
@@ -3927,6 +3928,8 @@ impl Index {
k: usize,
filter: Option<Box<QueryNode>>,
similarity: &str,
+ boost: Option<f32>,
+ min_similarity: Option<f32>,
) -> Result<SearchResult> {
let started = std::time::Instant::now();
@@ -4167,12 +4170,89 @@ impl Index {
}
}
+ // ── ES `knn.similarity` cutoff ─────────────────────────────────
+ // Convert the RAW-metric threshold into the equivalent
+ // transformed-score threshold (the same transform
+ // `compute_vector_similarity` applies to candidates) and drop
+ // everything below it BEFORE ranking, so `hits.total` reflects
+ // the cutoff — ES 8.13 excludes sub-threshold docs from hits AND
+ // total (live-verified 2026-07-12).
+ if let Some(raw) = min_similarity {
+ let cut = raw_similarity_to_score(similarity, raw);
+ scored.retain(|(_, s, _)| *s >= cut);
+ }
+ // ES applies `boost` to the final `_score` AFTER the similarity
+ // cutoff (a boosted sub-threshold doc stays excluded; a boosted
+ // passing doc scores `transform(sim) * boost`).
+ if let Some(b) = boost {
+ if (b - 1.0).abs() > f32::EPSILON {
+ for (_, s, _) in scored.iter_mut() {
+ *s *= b;
+ }
+ }
+ }
+
// ── Rank, cap the candidate pool at k, then paginate ──────────
// (shared with the HNSW path so hits format / total semantics
// cannot drift between the exact and approximate executors)
Ok(knn_result_from_scored(request, scored, k, started))
}
+ /// PURE multi-KNN executor (the ES top-level `knn: [...]` array form,
+ /// synthesised by the compat layer as `bool.should` of Knn nodes).
+ ///
+ /// ES 8.13 semantics (live-verified 2026-07-12 against 8.13.4):
+ /// * each clause independently retrieves its own top `k_i`;
+ /// * a doc found by multiple clauses scores the SUM of its
+ /// per-clause scores (each already boosted/cut per clause);
+ /// * `hits.total` is the size of the deduplicated union.
+ async fn run_multi_knn_brute_force(
+ &self,
+ request: &SearchRequest,
+ clauses: Vec<PeeledKnn>,
+ ) -> Result<SearchResult> {
+ let started = std::time::Instant::now();
+ let mut merged: Vec<(String, f32, Value)> = Vec::new();
+ let mut slot_by_id: HashMap<String, usize> = HashMap::new();
+ let mut k_sum: usize = 0;
+ for clause in clauses {
+ k_sum = k_sum.saturating_add(clause.k);
+ let similarity = {
+ let schema = self.schema.read().await;
+ lookup_vector_similarity(&schema.schema, &clause.field)
+ };
+ // Per-clause top-k: window the sub-search to exactly the
+ // clause's own pool so the union matches ES's per-clause
+ // retrieval (from/size pagination applies to the MERGED
+ // list below, not to each clause).
+ let mut sub_request = request.clone();
+ sub_request.from = 0;
+ sub_request.size = clause.k;
+ let sub = self
+ .run_knn_brute_force(
+ &sub_request,
+ &clause.field,
+ &clause.vector,
+ clause.k,
+ clause.filter,
+ &similarity,
+ clause.boost,
+ clause.similarity,
+ )
+ .await?;
+ for hit in sub.hits {
+ match slot_by_id.get(&hit.id) {
+ Some(&i) => merged[i].1 += hit.score,
+ None => {
+ slot_by_id.insert(hit.id.clone(), merged.len());
+ merged.push((hit.id, hit.score, hit.source));
+ }
+ }
+ }
+ }
+ Ok(knn_result_from_scored(request, merged, k_sum, started))
+ }
+
/// Brute-force nested KNN: score each parent by the best (max)
/// similarity among its `<nested_path>` array elements.
///
@@ -4271,8 +4351,17 @@ impl Index {
)));
};
- self.run_knn_brute_force(request, &knn_field, &query_vec, k, filter, &similarity)
- .await
+ self.run_knn_brute_force(
+ request,
+ &knn_field,
+ &query_vec,
+ k,
+ filter,
+ &similarity,
+ None,
+ None,
+ )
+ .await
}
/// Auto-embed `semantic_text` fields on ingest.
@@ -5513,12 +5602,25 @@ impl Index {
// exact brute-force scan below. Filtered knn stays exact brute
// force with a pre-filter, where `num_candidates` (the ANN fan-out)
// has no effect.
- if let Some((field, query_vec, k, num_candidates, filter_opt)) = peel_knn_query(query) {
+ if let Some(peeled) = peel_knn_query(query) {
+ let PeeledKnn {
+ field,
+ vector: query_vec,
+ k,
+ num_candidates,
+ filter: filter_opt,
+ boost,
+ similarity: min_similarity,
+ } = peeled;
let similarity = {
let schema = self.schema.read().await;
lookup_vector_similarity(&schema.schema, &field)
};
- if filter_opt.is_none() {
+ // The HNSW ANN path serves only the PLAIN case: no filter, no
+ // boost, no similarity cutoff. Boost/cutoff requests go exact
+ // brute force where both are applied in the right order
+ // (cutoff on the unboosted transformed score, then boost).
+ if filter_opt.is_none() && boost.is_none() && min_similarity.is_none() {
if let Some(result) = self
.run_knn_hnsw(request, &field, &query_vec, k, num_candidates, &similarity)
.await
@@ -5527,9 +5629,25 @@ impl Index {
}
}
return self
- .run_knn_brute_force(request, &field, &query_vec, k, filter_opt, &similarity)
+ .run_knn_brute_force(
+ request,
+ &field,
+ &query_vec,
+ k,
+ filter_opt,
+ &similarity,
+ boost,
+ min_similarity,
+ )
.await;
}
+ // PURE multi-KNN (the ES `knn: [...]` array form): every clause runs
+ // its own exact top-k, scores are SUMMED for docs found by more than
+ // one clause, and `hits.total` is the size of the deduplicated union
+ // — matching ES 8.13 multi-kNN semantics (live-verified 2026-07-12).
+ if let Some(clauses) = peel_multi_knn_query(query) {
+ return self.run_multi_knn_brute_force(request, clauses).await;
+ }
// Nested `knn` query: `nested { path: P, query: { knn { field: P.vec } } }`.
// ES scores each parent by the best-matching nested element and
// returns parents in similarity-descending order. We implement
@@ -15232,6 +15350,30 @@ pub fn resolve_field_alias(schema: &Schema, field: &str) -> String {
/// scores stay byte-identical between the brute-force knn path and
/// the script_score-via-Painless path, which is what
/// 46_knn_search_bbq_ivf's "rescore vector consistency" tests assert.
+/// Convert an ES `knn.similarity` RAW-metric threshold into the equivalent
+/// transformed `_score` threshold, using the SAME transforms
+/// `compute_vector_similarity` applies to candidates:
+/// cosine / dot_product → (1 + raw) / 2
+/// l2_norm (raw = max distance) → 1 / (1 + raw²)
+/// max_inner_product → raw < 0 ? 1/(1 - raw) : raw + 1
+/// These mirror ES 8.13's `DenseVectorFieldMapper.VectorSimilarity#score`.
+fn raw_similarity_to_score(sim: &str, raw: f32) -> f32 {
+ let raw = raw as f64;
+ let score: f64 = match sim {
+ "l2_norm" => 1.0 / (1.0 + raw * raw),
+ "max_inner_product" => {
+ if raw < 0.0 {
+ 1.0 / (1.0 - raw)
+ } else {
+ raw + 1.0
+ }
+ }
+ // cosine (default) and dot_product share the same transform.
+ _ => (1.0 + raw) / 2.0,
+ };
+ score as f32
+}
+
fn compute_vector_similarity(sim: &str, a: &[f32], b: &[f32]) -> f32 {
debug_assert_eq!(a.len(), b.len());
let dot: f64 = a
@@ -15391,23 +15533,32 @@ fn collect_dense_vector_fields(schema: &Schema) -> Vec<String> {
out
}
+/// A top-level KNN query unwrapped for the short-circuit executor.
+#[derive(Debug, Clone)]
+struct PeeledKnn {
+ field: String,
+ vector: Vec<f32>,
+ k: usize,
+ num_candidates: Option<usize>,
+ filter: Option<Box<QueryNode>>,
+ /// Multiplied into every hit's score AFTER the similarity cutoff
+ /// (mirrors ES: the cutoff applies to raw similarity, boost to the
+ /// final `_score`). Wrapping `Boosted` nodes multiply in here too.
+ boost: Option<f32>,
+ /// ES `knn.similarity` raw-metric cutoff (see `QueryNode::Knn`).
+ similarity: Option<f32>,
+}
+
/// Unwrap a top-level Knn query, optionally nested under a single transparent
/// wrapper (Boosted, Constant, Named, or a single-clause Bool must/should).
-/// Returns `(field, query_vector, k, filter)` when the query is a KNN
-/// short-circuit candidate, `None` otherwise.
+/// Returns the peeled spec when the query is a KNN short-circuit candidate,
+/// `None` otherwise.
///
/// Filters attached to the Knn node are preserved; filters attached to the
-/// wrapping Bool are merged in via Bool::filter semantics.
-#[allow(clippy::type_complexity)]
-fn peel_knn_query(
- q: &QueryNode,
-) -> Option<(
- String,
- Vec<f32>,
- usize,
- Option<usize>,
- Option<Box<QueryNode>>,
-)> {
+/// wrapping Bool are merged in via Bool::filter semantics. A wrapping
+/// `Boosted` multiplies into the knn boost so `{"knn": {..., "boost": b}}`
+/// and `bool.should=[{knn}]`-style wrappers score identically to ES.
+fn peel_knn_query(q: &QueryNode) -> Option<PeeledKnn> {
match q {
QueryNode::Knn {
field,
@@ -15415,17 +15566,23 @@ fn peel_knn_query(
k,
num_candidates,
filter,
- ..
- } => Some((
- field.clone(),
- vector.clone(),
- *k,
- *num_candidates,
- filter.clone(),
- )),
- QueryNode::Constant { query, .. }
- | QueryNode::Boosted { query, .. }
- | QueryNode::Named { query, .. } => peel_knn_query(query),
+ boost,
+ similarity,
+ } => Some(PeeledKnn {
+ field: field.clone(),
+ vector: vector.clone(),
+ k: *k,
+ num_candidates: *num_candidates,
+ filter: filter.clone(),
+ boost: *boost,
+ similarity: *similarity,
+ }),
+ QueryNode::Boosted { query, boost } => {
+ let mut peeled = peel_knn_query(query)?;
+ peeled.boost = Some(boost * peeled.boost.unwrap_or(1.0));
+ Some(peeled)
+ }
+ QueryNode::Constant { query, .. } | QueryNode::Named { query, .. } => peel_knn_query(query),
QueryNode::Bool {
must,
should,
@@ -15442,13 +15599,13 @@ fn peel_knn_query(
if candidates.len() != 1 {
return None;
}
- let (f, v, k, nc, inner_filter) = peel_knn_query(candidates[0])?;
+ let mut peeled = peel_knn_query(candidates[0])?;
// Combine inner_filter + bool's filter clauses.
let mut merged_filters: Vec<QueryNode> = filter.clone();
- if let Some(fi) = inner_filter {
+ if let Some(fi) = peeled.filter.take() {
merged_filters.push(*fi);
}
- let final_filter: Option<Box<QueryNode>> = match merged_filters.len() {
+ peeled.filter = match merged_filters.len() {
0 => None,
1 => Some(Box::new(merged_filters.into_iter().next().unwrap())),
_ => Some(Box::new(QueryNode::Bool {
@@ -15459,7 +15616,43 @@ fn peel_knn_query(
minimum_should_match: None,
})),
};
- Some((f, v, k, nc, final_filter))
+ Some(peeled)
+ }
+ _ => None,
+ }
+}
+
+/// Unwrap a PURE multi-KNN query: a `bool` whose `should` clauses are ALL
+/// Knn nodes (>= 2) and nothing else. This is the shape the ES-compat layer
+/// synthesises for the top-level `knn: [...]` array form. Returns the peeled
+/// clauses, or `None` for any other shape (which falls through to the
+/// generic path, exactly as before).
+fn peel_multi_knn_query(q: &QueryNode) -> Option<Vec<PeeledKnn>> {
+ match q {
+ QueryNode::Named { query, .. } => peel_multi_knn_query(query),
+ QueryNode::Bool {
+ must,
+ should,
+ filter,
+ must_not,
+ minimum_should_match,
+ } => {
+ if !must.is_empty()
+ || !filter.is_empty()
+ || !must_not.is_empty()
+ || minimum_should_match.is_some()
+ || should.len() < 2
+ {
+ return None;
+ }
+ let mut out: Vec<PeeledKnn> = Vec::with_capacity(should.len());
+ for clause in should {
+ match clause {
+ QueryNode::Knn { .. } => out.push(peel_knn_query(clause)?),
+ _ => return None,
+ }
+ }
+ Some(out)
}
_ => None,
}
@@ -15713,7 +15906,14 @@ fn peel_nested_knn_query(
QueryNode::Nested { path, query, .. } => (path.clone(), query.as_ref()),
_ => return None,
};
- let (field, vector, k, num_candidates, inner_filter) = peel_knn_query(inner_q)?;
+ let peeled = peel_knn_query(inner_q)?;
+ let (field, vector, k, num_candidates, inner_filter) = (
+ peeled.field,
+ peeled.vector,
+ peeled.k,
+ peeled.num_candidates,
+ peeled.filter,
+ );
// Knn's own filter sub-query is a pre-filter.
let mut pre_all: Vec<QueryNode> = pre_filters;
if let Some(f) = inner_filter {
@@ -23709,6 +23909,7 @@ mod knn_num_candidates_tests {
num_candidates,
filter: None,
boost: None,
+ similarity: None,
}),
score_mode: None,
}
@@ -23745,11 +23946,78 @@ mod knn_num_candidates_tests {
num_candidates: Some(64),
filter: None,
boost: None,
+ similarity: None,
};
let peeled = peel_knn_query(&q).expect("knn peels");
- // Tuple: (field, vector, k, num_candidates, filter).
- assert_eq!(peeled.2, 5, "k");
- assert_eq!(peeled.3, Some(64), "num_candidates");
+ assert_eq!(peeled.k, 5, "k");
+ assert_eq!(peeled.num_candidates, Some(64), "num_candidates");
+ }
+
+ /// A wrapping `Boosted` multiplies into the peeled knn boost, and the
+ /// knn node's own `boost`/`similarity` are carried through the peel.
+ #[test]
+ fn peel_carries_boost_and_similarity() {
+ let inner = QueryNode::Knn {
+ field: "vec".into(),
+ vector: vec![0.1, 0.2],
+ k: 5,
+ num_candidates: None,
+ filter: None,
+ boost: Some(2.0),
+ similarity: Some(0.9),
+ };
+ let q = QueryNode::Boosted {
+ boost: 3.0,
+ query: Box::new(inner),
+ };
+ let peeled = peel_knn_query(&q).expect("knn peels");
+ assert_eq!(peeled.boost, Some(6.0), "outer boost multiplies inner");
+ assert_eq!(peeled.similarity, Some(0.9), "similarity carried");
+ }
+
+ /// `bool.should` of >= 2 knn clauses (the ES `knn: [...]` array form)
+ /// peels as a multi-knn; any non-knn sibling clause disqualifies it.
+ #[test]
+ fn peel_multi_knn_shapes() {
+ let knn = |x: f32| QueryNode::Knn {
+ field: "vec".into(),
+ vector: vec![x, 0.0],
+ k: 3,
+ num_candidates: None,
+ filter: None,
+ boost: None,
+ similarity: None,
+ };
+ let pure = QueryNode::Bool {
+ must: vec![],
+ should: vec![knn(1.0), knn(0.5)],
+ filter: vec![],
+ must_not: vec![],
+ minimum_should_match: None,
+ };
+ let clauses = peel_multi_knn_query(&pure).expect("pure multi-knn peels");
+ assert_eq!(clauses.len(), 2);
+ assert_eq!(clauses[0].k, 3);
+
+ let hybrid = QueryNode::Bool {
+ must: vec![],
+ should: vec![
+ knn(1.0),
+ QueryNode::Term {
+ field: "tag".into(),
+ value: serde_json::json!("a"),
+ boost: None,
+ },
+ knn(0.5),
+ ],
+ filter: vec![],
+ must_not: vec![],
+ minimum_should_match: None,
+ };
+ assert!(
+ peel_multi_knn_query(&hybrid).is_none(),
+ "non-knn sibling must fall through to the generic path"
+ );
}
}
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index 8d6b229c0..5da8d2e99 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -4843,3 +4843,114 @@ async fn test_restore_snapshot_honors_indices_filter() {
);
}
+/// Blocker 7: top-level kNN semantics, verified against live ES 8.13.4 on
+/// 2026-07-12 with this exact corpus:
+/// * `knn.filter` pre-filters candidates (ES returned ids 1,3);
+/// * `knn.similarity` (raw cosine cutoff) drops sub-threshold docs from
+/// hits AND `hits.total` (ES: total 2, ids 1,2);
+/// * `boost` multiplies scores AFTER the cutoff (ES: 2.0 / ~1.9939);
+/// * multiple knn clauses (`bool.should` of Knn nodes — the compat layer's
+/// synthesis of the `knn: [...]` array) run per-clause top-k and SUM
+/// scores over the union (ES: total 2, both scored 1.0).
+#[tokio::test]
+async fn test_knn_filter_similarity_boost_and_multi_clause() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+
+ let mut schema = Schema::empty();
+ let mut vf = FieldConfig::new("v", FieldType::Vector);
+ vf.options.dimensions = Some(3);
+ vf.options.similarity = Some("cosine".to_string());
+ schema.fields.push(vf);
+ schema
+ .fields
+ .push(FieldConfig::new("tag", FieldType::Keyword));
+ engine.create_index("knnidx", schema).unwrap();
+ let idx = engine.get_index("knnidx").unwrap();
+
+ idx.index_document(Some("1".into()), json!({"v": [1.0, 0.0, 0.0], "tag": "a"}))
+ .await
+ .unwrap();
+ idx.index_document(Some("2".into()), json!({"v": [0.9, 0.1, 0.0], "tag": "b"}))
+ .await
+ .unwrap();
+ idx.index_document(Some("3".into()), json!({"v": [0.0, 1.0, 0.0], "tag": "a"}))
+ .await
+ .unwrap();
+
+ let run = |body: Value| {
+ let req = parse_request(&body).expect("parse_request");
+ let idx = idx.clone();
+ async move { idx.search(&req).await.unwrap() }
+ };
+
+ // knn.filter: only tag=a docs may enter the top-k (ES: ids 1,3).
+ let filtered = run(json!({
+ "query": {"knn": {"field": "v", "query_vector": [1.0, 0.0, 0.0], "k": 2,
+ "filter": {"term": {"tag": "a"}}}},
+ "size": 10
+ }))
+ .await;
+ let ids: Vec<&str> = filtered.hits.iter().map(|h| h.id.as_str()).collect();
+ assert_eq!(
+ ids,
+ vec!["1", "3"],
+ "filter must exclude tag=b from the pool"
+ );
+
+ // knn.similarity: raw cosine cutoff 0.9 keeps ids 1,2 only, and the
+ // excluded doc leaves hits.total too (ES: total 2).
+ let cut = run(json!({
+ "query": {"knn": {"field": "v", "query_vector": [1.0, 0.0, 0.0], "k": 3,
+ "similarity": 0.9}},
+ "size": 10
+ }))
+ .await;
+ assert_eq!(
+ cut.total.value, 2,
+ "sub-threshold doc must leave hits.total"
+ );
+ let ids: Vec<&str> = cut.hits.iter().map(|h| h.id.as_str()).collect();
+ assert_eq!(ids, vec!["1", "2"]);
+
+ // boost multiplies AFTER the cutoff (ES: scores 2.0 and ~1.9939).
+ let boosted = run(json!({
+ "query": {"knn": {"field": "v", "query_vector": [1.0, 0.0, 0.0], "k": 3,
+ "similarity": 0.9, "boost": 2.0}},
+ "size": 10
+ }))
+ .await;
+ assert_eq!(boosted.total.value, 2);
+ assert!(
+ (boosted.hits[0].score - 2.0).abs() < 1e-3,
+ "top score must be 2.0, got {}",
+ boosted.hits[0].score
+ );
+ assert!(
+ (boosted.hits[1].score - 1.9939).abs() < 1e-3,
+ "second score must be ~1.9939, got {}",
+ boosted.hits[1].score
+ );
+
+ // Multi-knn union: per-clause top-1, summed scores over the dedup'd
+ // union (ES: total 2, ids {1,3}, each scored 1.0).
+ let multi = run(json!({
+ "query": {"bool": {"should": [
+ {"knn": {"field": "v", "query_vector": [1.0, 0.0, 0.0], "k": 1}},
+ {"knn": {"field": "v", "query_vector": [0.0, 1.0, 0.0], "k": 1}}
+ ]}},
+ "size": 10
+ }))
+ .await;
+ assert_eq!(multi.total.value, 2, "union of the two top-1 pools");
+ let mut ids: Vec<&str> = multi.hits.iter().map(|h| h.id.as_str()).collect();
+ ids.sort_unstable();
+ assert_eq!(ids, vec!["1", "3"]);
+ for h in &multi.hits {
+ assert!(
+ (h.score - 1.0).abs() < 1e-3,
+ "per-clause exact-match scores must both be 1.0, got {}",
+ h.score
+ );
+ }
+}
diff --git a/engine/crates/xerj-query/src/ast.rs b/engine/crates/xerj-query/src/ast.rs
index 9c24b0e92..bc7830d8b 100644
--- a/engine/crates/xerj-query/src/ast.rs
+++ b/engine/crates/xerj-query/src/ast.rs
@@ -444,6 +444,12 @@ pub enum QueryNode {
filter: Option<Box<QueryNode>>,
#[serde(skip_serializing_if = "Option::is_none")]
boost: Option<f32>,
+ /// ES `knn.similarity`: the minimum RAW similarity (in the field's
+ /// metric space — cosine value, dot product, or l2 distance) a
+ /// vector must reach to count as a match. Docs below the cutoff
+ /// are excluded from hits AND from `hits.total`. `None` = no cutoff.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ similarity: Option<f32>,
},
/// Natural-language semantic search — text is embedded at query time.
diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rs
index 1ee725791..e73e4d2b5 100644
--- a/engine/crates/xerj-query/src/parser.rs
+++ b/engine/crates/xerj-query/src/parser.rs
@@ -2273,14 +2273,37 @@ fn parse_knn(params: &Value) -> Result<QueryNode> {
})
.collect::<Result<Vec<f32>>>()?;
- let filter = obj
- .get("filter")
- .map(parse_query)
- .transpose()?
- .map(Box::new);
+ // ES accepts `filter` as a single query object OR an array of queries
+ // (implicitly ANDed, exactly like `bool.filter`).
+ let filter = match obj.get("filter") {
+ None => None,
+ Some(Value::Array(arr)) => {
+ let parsed: Vec<QueryNode> = arr.iter().map(parse_query).collect::<Result<_>>()?;
+ match parsed.len() {
+ 0 => None,
+ 1 => Some(Box::new(parsed.into_iter().next().unwrap())),
+ _ => Some(Box::new(QueryNode::Bool {
+ must: Vec::new(),
+ should: Vec::new(),
+ filter: parsed,
+ must_not: Vec::new(),
+ minimum_should_match: None,
+ })),
+ }
+ }
+ Some(single) => Some(Box::new(parse_query(single)?)),
+ };
let boost = obj.get("boost").and_then(|v| v.as_f64()).map(|b| b as f32);
+ // ES `knn.similarity` — raw-metric similarity cutoff (docs below it
+ // are not matches). Kept raw here; the executor converts it into the
+ // equivalent transformed-score threshold per the field's metric.
+ let similarity = obj
+ .get("similarity")
+ .and_then(|v| v.as_f64())
+ .map(|s| s as f32);
+
Ok(QueryNode::Knn {
field,
vector,
@@ -2288,6 +2311,7 @@ fn parse_knn(params: &Value) -> Result<QueryNode> {
num_candidates,
filter,
boost,
+ similarity,
})
}
diff --git a/engine/crates/xerj-query/src/planner.rs b/engine/crates/xerj-query/src/planner.rs
index 704d8b824..d1b905664 100644
--- a/engine/crates/xerj-query/src/planner.rs
+++ b/engine/crates/xerj-query/src/planner.rs
@@ -749,6 +749,7 @@ mod tests {
num_candidates: None,
filter: None,
boost: None,
+ similarity: None,
},
term_node("status", "ok"),
],
@@ -788,6 +789,7 @@ mod tests {
num_candidates: None,
filter: None,
boost: None,
+ similarity: None,
};
let plan = plan_query(q, &empty_schema()).unwrap();
assert!(matches!(plan, ExecutionPlan::VectorScan { k: 20, .. }));
@@ -809,6 +811,7 @@ mod tests {
num_candidates: None,
filter: None,
boost: None,
+ similarity: None,
},
weight: 0.5,
},
diff --git a/engine/crates/xerj-query/src/rewriter.rs b/engine/crates/xerj-query/src/rewriter.rs
index cbbc3aef8..2169b0561 100644
--- a/engine/crates/xerj-query/src/rewriter.rs
+++ b/engine/crates/xerj-query/src/rewriter.rs
@@ -213,6 +213,7 @@ fn rewrite_once(query: QueryNode) -> (QueryNode, bool) {
num_candidates,
filter,
boost,
+ similarity,
} => match filter {
None => (
QueryNode::Knn {
@@ -222,6 +223,7 @@ fn rewrite_once(query: QueryNode) -> (QueryNode, bool) {
num_candidates,
filter: None,
boost,
+ similarity,
},
false,
),
@@ -235,6 +237,7 @@ fn rewrite_once(query: QueryNode) -> (QueryNode, bool) {
num_candidates,
filter: Some(Box::new(f2)),
boost,
+ similarity,
},
changed,
)