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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(search): multi_match returned _score 0.0 for every hit — zero default bool boost + ES best_fields dis_max
xerj-org9809b49a298a
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 2fa900488..09c07ed23 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -15,7 +15,7 @@ use xerj_common::schema::ManagedSchema;use xerj_common::types::{FieldConfig, FieldType, IndexName, Schema};use xerj_fts::analyzer::AnalyzerRegistry;use xerj_fts::index::{FtsIndexReader, FtsIndexWriter};-use xerj_fts::search::{FtsSearcher, Query as FtsQuery, TermQuery as FtsTerm, BoolQuery as FtsBool};+use xerj_fts::search::{FtsSearcher, Query as FtsQuery, TermQuery as FtsTerm, BoolQuery as FtsBool, DisMaxQuery as FtsDisMax};use regex::Regex;use xerj_query::ast::{BoostMode, FieldValueFactor, Fuzziness, HighlightRequest, MinShouldMatch, Modifier, QueryNode, RandomScore, RescoreQuery, ScoreFunction, ScoreMode, SearchRequest, SourceFilter, TrackTotalHits};use xerj_query::executor::{Hit, SearchResult, TotalHits, TotalHitsRelation};@@ -10758,24 +10758,38 @@ fn score_query_against_doc(q: &QueryNode, source: &Value) -> f32 {if score == 0.0 { 1.0 } else { score }}QueryNode::Named { query, .. } => score_query_against_doc(query, source),- // MultiMatch with field boosts: sum boosted scores across matching fields.- QueryNode::MultiMatch { fields, query, boost, .. } => {+ // MultiMatch with field boosts. ES semantics per type:+ // best_fields (default) → dis_max: MAX of the per-field scores.+ // most_fields → sum of the per-field scores.+ QueryNode::MultiMatch { fields, query, boost, match_type, .. } => {let q_lower = query.to_lowercase();let outer_boost = boost.unwrap_or(1.0);- let mut total_score = 0.0f32;+ let mut sum_score = 0.0f32;+ let mut max_score = 0.0f32;let mut matched = false;for field_spec in fields {let (field, field_boost) = parse_field_boost(field_spec);if let Some(v) = get_field_value(source, field) {if let Value::String(s) = v {if s.to_lowercase().contains(&q_lower) {- total_score += field_boost;+ sum_score += field_boost;+ if field_boost > max_score {+ max_score = field_boost;+ }matched = true;}}}}- if matched { total_score * outer_boost } else { 0.0 }+ if !matched {+ return 0.0;+ }+ let combined = if matches!(match_type, xerj_query::ast::MultiMatchType::MostFields) {+ sum_score+ } else {+ max_score+ };+ combined * outer_boost}QueryNode::FunctionScore { query, functions, score_mode, boost_mode, .. } => {// Score the inner query, then run the function scores against@@ -11300,32 +11314,72 @@ fn query_node_to_fts(q: &QueryNode, text_fields: &[String]) -> Option<FtsQuery>}Some(FtsQuery::Bool(Box::new(bool_q)))}- QueryNode::MultiMatch { query, fields, .. } => {+ QueryNode::MultiMatch { query, fields, match_type, boost, .. } => {let registry = AnalyzerRegistry::default();let analyzer = registry.get_analyzer("standard")?;let tokens = analyzer.analyze(query);if tokens.is_empty() {return None;}- // Strip boost factors from field specs (e.g. "title^3" → "title").- let owned_fields: Vec<String>;- let search_fields: Vec<&str> = if fields.is_empty() {- text_fields.iter().map(|s| s.as_str()).collect::<Vec<_>>()+ // Split boost factors out of field specs (e.g. "title^3" → ("title", 3.0)).+ let field_specs: Vec<(String, f32)> = if fields.is_empty() {+ text_fields.iter().map(|s| (s.clone(), 1.0)).collect()} else {- owned_fields = fields+ fields.iter()- .map(|s| parse_field_boost(s).0.to_string())- .collect();- owned_fields.iter().map(|s| s.as_str()).collect()+ .map(|s| {+ let (f, b) = parse_field_boost(s);+ (f.to_string(), b)+ })+ .collect()};- let mut bool_q = FtsBool::new();- for field in &search_fields {- for token in &tokens {- bool_q =- bool_q.should(FtsQuery::Term(FtsTerm::new(*field, &token.text)));+ if field_specs.is_empty() {+ return None;+ }+ // One scored clause per field. A single-token query lowers to a+ // bare Term so that `multi_match(q, [f])` scores IDENTICALLY to+ // `match {f: q}`; multi-token queries lower to an OR-bool over the+ // tokens (per-field score = Σ token BM25) — same as the Match+ // lowering above. Per-field `^boost` multiplies that field's score.+ let mut per_field: Vec<FtsQuery> = Vec::with_capacity(field_specs.len());+ for (field, fb) in &field_specs {+ if tokens.len() == 1 {+ per_field.push(FtsQuery::Term(FtsTerm::boosted(+ field.as_str(),+ &tokens[0].text,+ *fb,+ )));+ } else {+ let mut field_bool = FtsBool::new().boost(*fb);+ for token in &tokens {+ field_bool = field_bool+ .should(FtsQuery::Term(FtsTerm::new(field.as_str(), &token.text)));+ }+ per_field.push(FtsQuery::Bool(Box::new(field_bool)));}}- Some(FtsQuery::Bool(Box::new(bool_q)))+ // Combine per-field scores according to the multi_match type:+ // best_fields (ES default) → dis_max: score = MAX field score.+ // most_fields / everything else currently modeled → bool.should:+ // score = Σ field scores (pre-existing behaviour, now non-zero).+ let combined = if per_field.len() == 1 {+ per_field.pop().unwrap()+ } else if matches!(match_type, xerj_query::ast::MultiMatchType::BestFields) {+ FtsQuery::DisMax(Box::new(FtsDisMax::new(per_field)))+ } else {+ let mut bool_q = FtsBool::new();+ for clause in per_field {+ bool_q = bool_q.should(clause);+ }+ FtsQuery::Bool(Box::new(bool_q))+ };+ // Apply the outer `multi_match.boost` (if any) via a wrapping bool.+ let outer = boost.unwrap_or(1.0);+ if (outer - 1.0).abs() > f32::EPSILON {+ Some(FtsQuery::Bool(Box::new(FtsBool::new().should(combined).boost(outer))))+ } else {+ Some(combined)+ }}QueryNode::Term { .. } => {// Term queries are routed through stored-doc scanningdiff --git a/engine/crates/xerj-engine/tests/multi_match_scoring.rs b/engine/crates/xerj-engine/tests/multi_match_scoring.rsnew file mode 100644index 000000000..39aa9d14b--- /dev/null+++ b/engine/crates/xerj-engine/tests/multi_match_scoring.rs@@ -0,0 +1,132 @@+//! Regression tests: `multi_match` must return non-zero, ES-shaped scores.+//!+//! Bug: every multi_match hit came back with `_score: 0.0` on the segment+//! FTS path because `BoolQuery::new()` defaulted `boost` to 0.0 and+//! `execute_bool` multiplies the combined score by it. ES 8.x semantics:+//! `best_fields` (the default type) is a dis_max over per-field match+//! queries — the hit score is the MAX of the per-field scores; a+//! single-field multi_match scores identically to the equivalent `match`.++use std::collections::HashMap;++use serde_json::{json, Value};+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::Schema;+use xerj_engine::Engine;+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 req(q: Value) -> xerj_query::ast::SearchRequest {+ parse_request(&json!({ "query": q, "size": 50 })).expect("parse_request")+}++#[tokio::test]+async fn multi_match_scores_nonzero_and_best_fields_takes_field_max() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("mm", Schema::empty()).unwrap();+ let idx = engine.get_index("mm").unwrap();++ // 20 docs: "golf" in msg for i % 3 == 0, in note for i % 5 == 0, so the+ // multi_match union (9 docs: i%3==0 or i%5==0) differs from either+ // single-field result (7 via msg, 4 via note, 2 overlap).+ for i in 0..20 {+ let msg = if i % 3 == 0 {+ format!("user played golf round {i}")+ } else {+ format!("user played tennis {i}")+ };+ let note = if i % 5 == 0 { "golf note" } else { "misc" };+ idx.index_document(Some(format!("d{i}")), json!({"msg": msg, "note": note}))+ .await+ .unwrap();+ }++ // ── Memtable state: scores must not be zero ──────────────────────────+ let r = idx+ .search(&req(json!({"multi_match": {"query": "golf", "fields": ["msg", "note"]}})))+ .await+ .unwrap();+ assert_eq!(r.total.value, 9, "memtable multi_match union");+ for h in &r.hits {+ assert!(h.score > 0.0, "memtable multi_match hit {} scored 0.0", h.id);+ }++ // ── Segment state: BM25 scores, ES best_fields semantics ─────────────+ idx.flush().await.unwrap();++ let match_msg = idx.search(&req(json!({"match": {"msg": "golf"}}))).await.unwrap();+ let match_note = idx.search(&req(json!({"match": {"note": "golf"}}))).await.unwrap();+ let msg_scores: HashMap<&str, f32> =+ match_msg.hits.iter().map(|h| (h.id.as_str(), h.score)).collect();+ let note_scores: HashMap<&str, f32> =+ match_note.hits.iter().map(|h| (h.id.as_str(), h.score)).collect();+ assert!(match_msg.hits.iter().all(|h| h.score > 0.0));++ // Single-field multi_match must score IDENTICALLY to the match query.+ let mm_single = idx+ .search(&req(json!({"multi_match": {"query": "golf", "fields": ["msg"]}})))+ .await+ .unwrap();+ assert_eq!(mm_single.total.value, match_msg.total.value);+ for h in &mm_single.hits {+ let expected = msg_scores.get(h.id.as_str()).copied().unwrap_or(0.0);+ assert!(h.score > 0.0, "single-field multi_match hit {} scored 0.0", h.id);+ assert!(+ (h.score - expected).abs() < 1e-5,+ "hit {}: multi_match(msg) score {} != match(msg) score {}",+ h.id,+ h.score,+ expected+ );+ }++ // Multi-field best_fields: score = max(per-field match scores).+ let mm = idx+ .search(&req(json!({"multi_match": {"query": "golf", "fields": ["msg", "note"]}})))+ .await+ .unwrap();+ assert_eq!(mm.total.value, 9, "segment multi_match union");+ for h in &mm.hits {+ let ms = msg_scores.get(h.id.as_str()).copied().unwrap_or(0.0);+ let ns = note_scores.get(h.id.as_str()).copied().unwrap_or(0.0);+ let expected = ms.max(ns);+ assert!(h.score > 0.0, "multi-field multi_match hit {} scored 0.0", h.id);+ assert!(+ (h.score - expected).abs() < 1e-5,+ "hit {}: best_fields score {} != max(msg {}, note {})",+ h.id,+ h.score,+ ms,+ ns+ );+ }++ // most_fields: score = sum of the per-field scores.+ let mm_most = idx+ .search(&req(json!({+ "multi_match": {"query": "golf", "fields": ["msg", "note"], "type": "most_fields"}+ })))+ .await+ .unwrap();+ assert_eq!(mm_most.total.value, 9);+ for h in &mm_most.hits {+ let ms = msg_scores.get(h.id.as_str()).copied().unwrap_or(0.0);+ let ns = note_scores.get(h.id.as_str()).copied().unwrap_or(0.0);+ let expected = ms + ns;+ assert!(+ (h.score - expected).abs() < 1e-5,+ "hit {}: most_fields score {} != sum(msg {}, note {})",+ h.id,+ h.score,+ ms,+ ns+ );+ }+}diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rsindex 0ceaba7dc..7c0aad250 100644--- a/engine/crates/xerj-fts/src/search.rs+++ b/engine/crates/xerj-fts/src/search.rs@@ -148,7 +148,7 @@ impl PrefixQuery {}/// Boolean combinator query — mirrors Elasticsearch's `bool` query.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct BoolQuery {/// All must clauses must match.#[serde(default)]@@ -166,6 +166,55 @@ pub struct BoolQuery {pub boost: f32,}+impl Default for BoolQuery {+ /// NOTE: `boost` must default to **1.0**, not `f32::default()` (0.0).+ /// A derived `Default` zeroed the boost, and because `execute_bool`+ /// multiplies the combined clause score by `boost`, every query built+ /// through `BoolQuery::new()` (multi_match, multi-token match, bool)+ /// returned `_score: 0.0` for all hits on the segment FTS path.+ fn default() -> Self {+ Self {+ must: Vec::new(),+ should: Vec::new(),+ must_not: Vec::new(),+ min_should_match: None,+ boost: 1.0,+ }+ }+}++/// Disjunction-max query — mirrors Elasticsearch's `dis_max`.+///+/// A document's score is the MAXIMUM of its sub-query scores, plus+/// `tie_breaker` × the sum of the remaining matching sub-query scores.+/// `multi_match` with `type: best_fields` (the ES default) lowers to this.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DisMaxQuery {+ pub queries: Vec<Query>,+ /// Fraction of the non-best sub-scores added on top of the max (ES+ /// default = 0.0, i.e. pure max).+ #[serde(default)]+ pub tie_breaker: f32,+ #[serde(default = "default_boost")]+ pub boost: f32,+}++impl DisMaxQuery {+ pub fn new(queries: Vec<Query>) -> Self {+ Self { queries, tie_breaker: 0.0, boost: 1.0 }+ }++ pub fn tie_breaker(mut self, t: f32) -> Self {+ self.tie_breaker = t;+ self+ }++ pub fn boost(mut self, b: f32) -> Self {+ self.boost = b;+ self+ }+}+/// Top-level query enum.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]@@ -174,6 +223,7 @@ pub enum Query {Phrase(PhraseQuery),Prefix(PrefixQuery),Bool(Box<BoolQuery>),+ DisMax(Box<DisMaxQuery>),MatchAll,}@@ -206,6 +256,7 @@ impl FtsSearcher {Query::Phrase(pq) => self.execute_phrase(pq, explain),Query::Prefix(pq) => self.execute_prefix(pq, explain),Query::Bool(bq) => self.execute_bool(bq, explain),+ Query::DisMax(dq) => self.execute_dis_max(dq, explain),Query::MatchAll => self.execute_match_all(),}}@@ -522,6 +573,33 @@ impl FtsSearcher {Ok(hits)}+ // ── Dis-max query ─────────────────────────────────────────────────────────++ /// ES `dis_max` scoring: docs matching ANY sub-query are candidates;+ /// score = max(sub scores) + tie_breaker × Σ(other matching sub scores),+ /// all multiplied by the query boost.+ fn execute_dis_max(&self, dq: &DisMaxQuery, explain: bool) -> Result<Vec<ScoredHit>> {+ // Per-doc (max, sum) accumulator over sub-query scores.+ let mut acc: std::collections::HashMap<u32, (f32, f32)> =+ std::collections::HashMap::new();+ for sub in &dq.queries {+ for hit in self.execute(sub, explain)? {+ let e = acc.entry(hit.doc_id).or_insert((f32::NEG_INFINITY, 0.0));+ if hit.score > e.0 {+ e.0 = hit.score;+ }+ e.1 += hit.score;+ }+ }+ Ok(acc+ .into_iter()+ .map(|(doc_id, (max, sum))| {+ let score = (max + dq.tie_breaker * (sum - max)) * dq.boost;+ ScoredHit { doc_id, score, explanation: None }+ })+ .collect())+ }+// ── Match all ─────────────────────────────────────────────────────────────fn execute_match_all(&self) -> Result<Vec<ScoredHit>> {@@ -759,6 +837,117 @@ mod tests {assert!(!doc_ids.contains(&4), "doc4 should NOT match (no 'quick')");}+ #[test]+ fn bool_query_should_scores_are_nonzero() {+ // Regression: BoolQuery's derived Default gave boost = 0.0, so every+ // bool-shaped query (multi_match, multi-token match) returned+ // _score 0.0 for all hits. The default boost must be 1.0, and a+ // single-should bool must score identically to the bare term query.+ let dir = TempDir::new().unwrap();+ let searcher = setup_searcher(dir.path());++ let term_hits = searcher+ .search(&Query::Term(TermQuery::new("body", "fox")), 10, false)+ .unwrap();+ let bool_hits = searcher+ .search(+ &Query::Bool(Box::new(+ BoolQuery::new().should(Query::Term(TermQuery::new("body", "fox"))),+ )),+ 10,+ false,+ )+ .unwrap();++ assert_eq!(term_hits.len(), bool_hits.len());+ for th in &term_hits {+ assert!(th.score > 0.0, "term score must be positive");+ let bh = bool_hits.iter().find(|h| h.doc_id == th.doc_id).unwrap();+ assert!(+ (bh.score - th.score).abs() < 1e-6,+ "bool(should:[term]) score {} must equal term score {} for doc {}",+ bh.score,+ th.score,+ th.doc_id+ );+ }+ }++ #[test]+ fn dis_max_takes_max_of_subquery_scores() {+ let dir = TempDir::new().unwrap();+ let registry = Arc::new(AnalyzerRegistry::default());+ let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(®istry));+ let mut cfg = FieldIndexConfig::default();+ cfg.analyzer = "whitespace".to_owned();+ writer.configure_field("title", cfg.clone());+ writer.configure_field("body", cfg);++ // doc 0: "golf" in both fields; doc 1: only title; doc 2: only body.+ let docs: Vec<(&str, &str)> = vec![+ ("golf highlights", "golf swing tips and golf drills"),+ ("golf weekly", "tennis recap"),+ ("morning news", "golf scores from sunday"),+ ];+ for (i, (title, body)) in docs.iter().enumerate() {+ let fields: HashMap<String, String> = [+ ("title".to_owned(), title.to_string()),+ ("body".to_owned(), body.to_string()),+ ]+ .into_iter()+ .collect();+ writer.add_document(i as u32, &fields);+ }+ writer.finish().unwrap();+ let reader =+ Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["title", "body"]).unwrap());+ let searcher = FtsSearcher::new(reader, registry);++ let title_q = Query::Term(TermQuery::new("title", "golf"));+ let body_q = Query::Term(TermQuery::new("body", "golf"));+ let title_hits = searcher.search(&title_q, 10, false).unwrap();+ let body_hits = searcher.search(&body_q, 10, false).unwrap();++ let dm = Query::DisMax(Box::new(DisMaxQuery::new(vec![+ title_q.clone(),+ body_q.clone(),+ ])));+ let dm_hits = searcher.search(&dm, 10, false).unwrap();++ // Union of matching docs: all three.+ assert_eq!(dm_hits.len(), 3, "dis_max must return the union of sub-query docs");++ for hit in &dm_hits {+ let ts = title_hits.iter().find(|h| h.doc_id == hit.doc_id).map(|h| h.score);+ let bs = body_hits.iter().find(|h| h.doc_id == hit.doc_id).map(|h| h.score);+ let expected = ts.unwrap_or(0.0).max(bs.unwrap_or(0.0));+ assert!(hit.score > 0.0, "dis_max hit must have positive score");+ assert!(+ (hit.score - expected).abs() < 1e-6,+ "doc {}: dis_max score {} != max(field scores) {}",+ hit.doc_id,+ hit.score,+ expected+ );+ }++ // tie_breaker adds a fraction of the non-best scores on top of the max.+ let dm_tb = Query::DisMax(Box::new(+ DisMaxQuery::new(vec![title_q, body_q]).tie_breaker(0.5),+ ));+ let tb_hits = searcher.search(&dm_tb, 10, false).unwrap();+ let both = tb_hits.iter().find(|h| h.doc_id == 0).unwrap();+ let ts = title_hits.iter().find(|h| h.doc_id == 0).unwrap().score;+ let bs = body_hits.iter().find(|h| h.doc_id == 0).unwrap().score;+ let expected = ts.max(bs) + 0.5 * (ts + bs - ts.max(bs));+ assert!(+ (both.score - expected).abs() < 1e-6,+ "tie_breaker score {} != expected {}",+ both.score,+ expected+ );+ }+#[test]fn bool_query_must_not_excludes() {let dir = TempDir::new().unwrap();