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(engine): score a keyword+text best_fields multi_match by dis_max, not sum (#572)

xerj-org19df0bbebdff
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index e7ab1ddf9..70915e725 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -32460,6 +32460,7 @@ fn rewrite_keyword_full_text_to_term(q: &QueryNode, schema: &Schema) -> QueryNod
fields,
query,
boost,
+ match_type,
..
} if fields
.iter()
@@ -32504,6 +32505,19 @@ fn rewrite_keyword_full_text_to_term(q: &QueryNode, schema: &Schema) -> QueryNod
}
if should.len() == 1 {
should.into_iter().next().unwrap()
+ } else if matches!(match_type, xerj_query::ast::MultiMatchType::BestFields) {
+ // #572: `best_fields` (the ES default) is a dis_max — the
+ // keyword `Term`(s) and the text `multi_match` combine by MAX
+ // (+ tie_breaker 0.0), not the SUM a `Bool.should` gives. This
+ // mirrors the all-text per-field combination in
+ // `query_node_to_fts_with_keyword_fields`, so a doc matching
+ // both halves scores `max(keyword, text)` as ES does, not the
+ // sum. `most_fields` stays a `should` (ES sums it), and
+ // `cross_fields`/phrase variants are a separate concern (#572).
+ QueryNode::DisMax {
+ queries: should,
+ tie_breaker: 0.0,
+ }
} else {
QueryNode::Bool {
must: Vec::new(),
@@ -39660,6 +39674,38 @@ fn query_node_to_fts_with_keyword_fields(
Some(combined)
}
}
+ // #572: a rewritten `best_fields` keyword split (keyword `Term`(s) + a
+ // text `multi_match`) reaches the segment path as a `DisMax`. Project
+ // each child and combine by MAX so the segment scores it like ES — and
+ // like the memtable — instead of declining FTS projection and dropping
+ // to the schema-blind stored-source scan (which SUMS the children).
+ // Decline only when a child cannot project, so a single DisMax never
+ // mixes FTS and fallback scoring.
+ QueryNode::DisMax {
+ queries,
+ tie_breaker,
+ } => {
+ let children: Vec<FtsQuery> = queries
+ .iter()
+ .filter_map(|c| {
+ query_node_to_fts_with_keyword_fields(
+ c,
+ text_fields,
+ exact_fields,
+ keyword_fields,
+ )
+ })
+ .collect();
+ if children.is_empty() || children.len() != queries.len() {
+ None
+ } else if children.len() == 1 {
+ children.into_iter().next()
+ } else {
+ Some(FtsQuery::DisMax(Box::new(
+ FtsDisMax::new(children).tie_breaker(*tie_breaker),
+ )))
+ }
+ }
QueryNode::Term {
field,
value,
diff --git a/engine/crates/xerj-engine/tests/keyword_match_is_mapping_aware.rs b/engine/crates/xerj-engine/tests/keyword_match_is_mapping_aware.rs
index 4b21d739b..1b00ddc05 100644
--- a/engine/crates/xerj-engine/tests/keyword_match_is_mapping_aware.rs
+++ b/engine/crates/xerj-engine/tests/keyword_match_is_mapping_aware.rs
@@ -53,6 +53,17 @@ fn expect(ids: &[&str]) -> BTreeSet<String> {
ids.iter().map(|s| s.to_string()).collect()
}
+async fn score_of(idx: &Index, q: &Value, id: &str) -> f32 {
+ idx.search(&req(q.clone()))
+ .await
+ .unwrap()
+ .hits
+ .iter()
+ .find(|h| h.id == id)
+ .unwrap_or_else(|| panic!("doc {id} not in hits for {q}"))
+ .score
+}
+
/// A multi-token `match`/`multi_match` over a scalar `keyword` field must match
/// the value WHOLE (keyword analyzer) — so `"red blue"` never matches `"red"` —
/// identically before and after `flush()`. Fixed by rewriting keyword-targeted
@@ -183,3 +194,72 @@ async fn mixed_multi_match_splits_keyword_and_text() {
);
}
}
+
+/// #572: a `best_fields` multi_match spanning BOTH a keyword and a text field
+/// must combine the two halves by **dis_max** (MAX + tie_breaker), exactly as ES
+/// does — not the **SUM** a `Bool.should` gives. Hit sets are unchanged (pinned
+/// by `mixed_multi_match_splits_keyword_and_text`); this pins the `_score` in
+/// both the memtable and segment phases. Fail-before (the pre-fix `Bool.should`):
+/// the combined score equals `kw + text`, so both asserts below trip.
+#[tokio::test]
+async fn best_fields_multi_match_scores_keyword_and_text_by_max_not_sum() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+
+ let mut schema = Schema::empty();
+ schema
+ .fields
+ .push(FieldConfig::new("tags", FieldType::Keyword));
+ schema
+ .fields
+ .push(FieldConfig::new("body", FieldType::Text));
+ engine.create_index("mmscore", schema).unwrap();
+ let idx = engine.get_index("mmscore").unwrap();
+ // "1" matches BOTH halves of query "vip": keyword `tags == "vip"` (whole)
+ // AND text `body` contains "vip".
+ idx.index_document(
+ Some("1".into()),
+ json!({ "tags": "vip", "body": "vip lounge access" }),
+ )
+ .await
+ .unwrap();
+ // Extra docs skew each field's BM25 stats so the two half-scores differ,
+ // making MAX vs SUM unambiguous, and so both halves have matching peers.
+ idx.index_document(
+ Some("2".into()),
+ json!({ "tags": "guest", "body": "vip vip vip vip vip" }),
+ )
+ .await
+ .unwrap();
+ idx.index_document(
+ Some("3".into()),
+ json!({ "tags": "vip", "body": "nothing relevant here at all" }),
+ )
+ .await
+ .unwrap();
+
+ let both = json!({ "multi_match": { "query": "vip", "fields": ["tags", "body"] } });
+ let kw_only = json!({ "multi_match": { "query": "vip", "fields": ["tags"] } });
+ let text_only = json!({ "multi_match": { "query": "vip", "fields": ["body"] } });
+
+ for phase in ["pre-flush", "post-flush"] {
+ let s_both = score_of(&idx, &both, "1").await;
+ let s_kw = score_of(&idx, &kw_only, "1").await;
+ let s_text = score_of(&idx, &text_only, "1").await;
+ let max = s_kw.max(s_text);
+ let sum = s_kw + s_text;
+ assert!(
+ (s_both - max).abs() < 1e-3,
+ "{phase}: best_fields multi_match over [keyword, text] must score \
+ max(kw={s_kw}, text={s_text})={max} (dis_max), got {s_both} (#572)"
+ );
+ assert!(
+ s_both + 1e-3 < sum,
+ "{phase}: combined score {s_both} must be MAX, not the SUM \
+ kw+text={sum} a Bool.should gives (#572)"
+ );
+ if phase == "pre-flush" {
+ idx.flush().await.unwrap();
+ }
+ }
+}