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(es-compat): nested query scores parents by child score_mode (#836) (#862)

xerj-org12f77517c51f
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c27b81ac1..85475245f 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -40016,6 +40016,49 @@ fn score_query_against_doc(q: &QueryNode, source: &Value, schema: &Schema) -> f3
let dl = tokens.len().max(1) as f32;
1.0 / dl.sqrt()
}
+ // #836: a (lexical) nested query rolls the matching CHILDREN's scores
+ // into the parent score per `score_mode` (ES default `avg`), instead of
+ // a flat 1.0. Mirrors the Nested matching arm: strip the path prefix so
+ // the inner query resolves against a child object, score each MATCHING
+ // child, then combine. Same source-based path on memtable and segment,
+ // so the ranking is flush-invariant.
+ QueryNode::Nested {
+ path,
+ query,
+ score_mode,
+ } => {
+ let inner = strip_nested_path_in_query(query, path);
+ let child_scores: Vec<f32> = match get_field_value(source, path) {
+ Some(Value::Array(arr)) => arr
+ .iter()
+ .filter(|elem| doc_matches_query_typed(&inner, elem, schema))
+ .map(|elem| score_query_against_doc(&inner, elem, schema))
+ .collect(),
+ Some(elem @ Value::Object(_)) => {
+ if doc_matches_query_typed(&inner, &elem, schema) {
+ vec![score_query_against_doc(&inner, &elem, schema)]
+ } else {
+ Vec::new()
+ }
+ }
+ _ => Vec::new(),
+ };
+ if child_scores.is_empty() {
+ return 0.0;
+ }
+ match score_mode.as_deref().unwrap_or("avg") {
+ "max" => child_scores
+ .iter()
+ .copied()
+ .fold(f32::NEG_INFINITY, f32::max),
+ "min" => child_scores.iter().copied().fold(f32::INFINITY, f32::min),
+ "sum" => child_scores.iter().sum(),
+ // `none`: children scores are ignored — keep the flat contribution.
+ "none" => 1.0,
+ // `avg` (ES default) and any unrecognised mode.
+ _ => child_scores.iter().sum::<f32>() / child_scores.len() as f32,
+ }
+ }
other => {
if doc_matches_query_typed(other, source, schema) {
1.0
diff --git a/engine/crates/xerj-engine/tests/nested_score_mode.rs b/engine/crates/xerj-engine/tests/nested_score_mode.rs
new file mode 100644
index 000000000..f205624f8
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/nested_score_mode.rs
@@ -0,0 +1,78 @@
+//! #836: a (lexical) `nested` query must roll the matching children's scores
+//! into the parent score per `score_mode` (avg/max/sum/min), not score every
+//! matching parent a flat 1.0. The child that matches "expert" with a higher
+//! term frequency scores higher, so its parent must rank first. Asserted on the
+//! memtable AND after flush (the issue reports the flat score on both paths).
+
+use serde_json::json;
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_engine::Engine;
+use xerj_query::parse_request;
+
+async fn top_ids_and_scores(engine: &Engine, q: serde_json::Value) -> Vec<(String, f32)> {
+ let idx = engine.get_index("docs").expect("get index");
+ let req = parse_request(&json!({
+ "query": q,
+ "sort": [{ "_score": "desc" }],
+ "size": 10
+ }))
+ .expect("parse_request");
+ idx.search(&req)
+ .await
+ .expect("search")
+ .hits
+ .into_iter()
+ .map(|h| (h.id, h.score))
+ .collect()
+}
+
+#[tokio::test]
+async fn nested_query_ranks_parents_by_child_score() {
+ let dir = TempDir::new().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ let engine = Engine::new(config).expect("engine");
+
+ // Schemaless: `users` is a nested array of objects with a `bio` text field.
+ engine
+ .create_index("docs", xerj_common::types::Schema::empty())
+ .expect("create");
+ let idx = engine.get_index("docs").expect("get");
+ idx.index_document(
+ Some("p1".to_string()),
+ json!({ "users": [{ "bio": "expert" }] }),
+ )
+ .await
+ .expect("index p1");
+ idx.index_document(
+ Some("p2".to_string()),
+ json!({ "users": [{ "bio": "expert expert expert" }] }),
+ )
+ .await
+ .expect("index p2");
+
+ let q = json!({ "nested": {
+ "path": "users",
+ "query": { "match": { "users.bio": "expert" } },
+ "score_mode": "max"
+ }});
+
+ // Both parents match; p2's child matches "expert" with a higher TF, so under
+ // score_mode:max p2 must outrank p1 — on the memtable and after flush.
+ let pre = top_ids_and_scores(&engine, q.clone()).await;
+ idx.refresh().await.expect("refresh");
+ let post = top_ids_and_scores(&engine, q.clone()).await;
+
+ for (label, hits) in [("memtable", &pre), ("segment", &post)] {
+ assert_eq!(hits.len(), 2, "{label}: both parents match");
+ assert_eq!(hits[0].0, "p2", "{label}: p2 (higher child TF) ranks first");
+ assert_eq!(hits[1].0, "p1", "{label}: p1 second");
+ assert!(
+ hits[0].1 > hits[1].1,
+ "{label}: p2 score {} must exceed p1 score {} (not a flat 1.0)",
+ hits[0].1,
+ hits[1].1
+ );
+ }
+}