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): bool.filter and must_not are non-scoring; stop the page-local rescore overwriting exact BM25 (#361)

xerj-org2e9e1242587d
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 1936e2435..6d5db1416 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -15280,6 +15280,23 @@ impl Index {
// Set when scored_columnar already dropped the first `from` candidates
// (page-offset hydration) — the final pagination then skips 0.
let mut scored_from_applied = false;
+ // ── #361: request-level companion to `scored_fast_applied` ────────
+ // The segment FTS path (`fts_handled` below) also produces EXACT ES
+ // BM25, scored against index-wide statistics (#188), and the
+ // page-local IDF rescore further down must not overwrite it — that
+ // rescore derives its N from `final_hits.len()`, i.e. the RETURNED
+ // PAGE, so leaving it armed makes `_score` a function of `size`.
+ // `fts_handled` is a per-segment local, so accumulate here.
+ //
+ // The rescore is only skipped when EVERY arm that could contribute a
+ // hit was exact. `heuristic_scored_applied` starts true whenever the
+ // memtable holds documents — unflushed hits carry the IDF-less
+ // memtable/stored-scan score, and putting the two populations on one
+ // scale is precisely what the rescore was papering over until the
+ // score unification lands (#354 / #188). Mixed pages therefore keep
+ // today's behaviour; a fully-flushed index gets exact BM25.
+ let mut fts_scored_applied = false;
+ let mut heuristic_scored_applied = mem_doc_count > 0;
if let Some(plan) = &scored_plan {
if scored_fast_ready {
if let Some((hits, total, from_applied)) = self.scored_columnar(
@@ -15709,6 +15726,8 @@ impl Index {
// way for count-only and size>0 so the fall-through
// decision (and thus the count) agrees.
fts_handled = true;
+ // #361 — this segment's hits carry exact BM25.
+ fts_scored_applied = true;
// Exact count — identical for count_only and size>0.
// GHOST WINDOW (b7 DEFECT 1c): `seg_total` is the
// segment's PHYSICAL match count — between a flush
@@ -16211,6 +16230,11 @@ impl Index {
// returns correct results (just slower).
let scan_stored = scan_stored || (needs_fts && !fts_handled);
if !fts_handled && scan_stored {
+ // #361 — this segment's hits are scored by
+ // `score_query_against_doc` (no IDF, no length norm), so
+ // the page mixes score scales and the IDF rescore below
+ // stays armed.
+ heuristic_scored_applied = true;
// M2 G3: for Range queries, compute the matching doc-id
// set from the segment's on-disk sorted numeric index
// and pass it as a pre-filter so `scan_stored_section_into`
@@ -16965,7 +16989,14 @@ impl Index {
// (`!scored_fast_applied`: the columnar scored path already produced
// exact ES BM25 scores — this heuristic rescore would rewrite
// range-less scoring bools with ≥2 clauses.)
+ // (`exact_bm25_page`: #361 — the segment FTS path produced the same
+ // exact BM25 and needs the identical protection. Its N comes from
+ // `final_hits.len()`, so without this `_score` depends on `size` and
+ // `bool{must:[A],must:[B]}` ranks differently from the same clauses
+ // scoped with `post_filter`.)
+ let exact_bm25_page = fts_scored_applied && !heuristic_scored_applied;
if !scored_fast_applied
+ && !exact_bm25_page
&& !final_hits.is_empty()
&& request.sort.is_empty()
// Top-level constant_score: scores are the wrapper's constant —
@@ -17017,7 +17048,9 @@ impl Index {
// < 0.001 under exact BM25 — e.g. status:ok over the 100k bench
// corpus scores 0.012563465, but boosting×0.3 shapes go lower — and
// this data-dependent fallback would silently rewrite exact scores.)
+ // (`exact_bm25_page`: #361 — same argument for the segment FTS path.)
if !scored_fast_applied
+ && !exact_bm25_page
&& !final_hits.is_empty()
&& request.sort.is_empty()
// Top-level constant_score with a small boost (< 0.001) is a
@@ -34194,25 +34227,24 @@ fn score_query_against_doc(q: &QueryNode, source: &Value) -> f32 {
/// clauses. We only rescore this shape because mixed Bool trees (e.g.
/// match_bool_prefix → [Match, Prefix]) have per-clause scores that
/// would break if we zeroed out the non-Match contribution.
+///
+/// Only the SCORING children (`must`/`should`) are walked — see
+/// `BooleanClause.isScoring()` (BooleanClause.java:84-87).
fn query_uses_bool_text(q: &QueryNode) -> bool {
fn walk(q: &QueryNode) -> (u32, bool) {
match q {
- QueryNode::Bool {
- must,
- should,
- filter,
- must_not,
- ..
- } => {
+ QueryNode::Bool { must, should, .. } => {
let mut text_children = 0u32;
let mut any_disqualifying = false;
let mut any_sub_bool = false;
- for sub in must
- .iter()
- .chain(should.iter())
- .chain(filter.iter())
- .chain(must_not.iter())
- {
+ // SCORING clauses only. `BooleanClause.isScoring()` is
+ // `occur == MUST || occur == SHOULD`
+ // (BooleanClause.java:84-87), so `filter`/`must_not` children
+ // must neither count toward `text_children` nor disqualify
+ // the shape — counting them is what made
+ // `bool{must:[match], filter:[term]}` reach this rescore and
+ // lose its exact BM25 order (#361).
+ for sub in must.iter().chain(should.iter()) {
match sub {
QueryNode::Match { .. }
| QueryNode::MultiMatch { .. }
@@ -34292,13 +34324,12 @@ fn collect_match_field_terms(q: &QueryNode) -> Vec<(String, String, f32)> {
out.push((f.to_string(), query.clone(), mult * qb * fb));
}
}
- QueryNode::Bool {
- must,
- should,
- filter,
- ..
- } => {
- for sub in must.iter().chain(should.iter()).chain(filter.iter()) {
+ // SCORING clauses only — `filter`/`must_not` contribute nothing to
+ // `_score` (`BooleanClause.isScoring()`, BooleanClause.java:84-87),
+ // so their terms must not enter the rescore's weighting either
+ // (#361).
+ QueryNode::Bool { must, should, .. } => {
+ for sub in must.iter().chain(should.iter()) {
walk(sub, mult, out);
}
}
@@ -36037,7 +36068,11 @@ fn ip_matches_cidr(ip_str: &str, cidr: &str) -> Option<bool> {
/// Anything else keeps the conservative all-fields-present gate.
fn prune_missing_should_fields(q: &FtsQuery, has_field: &dyn Fn(&str) -> bool) -> Option<FtsQuery> {
let FtsQuery::Bool(b) = q else { return None };
- if !b.must.is_empty() || !b.must_not.is_empty() || b.min_should_match.is_some() {
+ if !b.must.is_empty()
+ || !b.must_not.is_empty()
+ || !b.filter.is_empty()
+ || b.min_should_match.is_some()
+ {
return None;
}
if b.should.is_empty() || !b.should.iter().all(|c| matches!(c, FtsQuery::Term(_))) {
@@ -36143,11 +36178,16 @@ fn collect_fts_query_fields(q: &FtsQuery, out: &mut Vec<String>) {
}
}
FtsQuery::Bool(b) => {
+ // `filter` too: a non-scoring clause still names a field the
+ // segment must have FTS data for, and the caller's
+ // "reader has EVERY queried field" gate is what routes a
+ // segment missing it onto the stored-doc scan.
for sub in b
.must
.iter()
.chain(b.should.iter())
.chain(b.must_not.iter())
+ .chain(b.filter.iter())
{
collect_fts_query_fields(sub, out);
}
@@ -36194,11 +36234,16 @@ fn collect_fts_query_terms(q: &FtsQuery, out: &mut Vec<(String, String)>) {
}
FtsQuery::Prefix(_) | FtsQuery::Wildcard(_) | FtsQuery::Fuzzy(_) | FtsQuery::MatchAll => {}
FtsQuery::Bool(b) => {
+ // `filter` is non-scoring, so its df never reaches a `_score`;
+ // it is collected anyway because the clause is still EXECUTED
+ // (its hits are what narrows the conjunction) and an index-wide
+ // df keeps that execution identical across segments.
for sub in b
.must
.iter()
.chain(b.should.iter())
.chain(b.must_not.iter())
+ .chain(b.filter.iter())
{
collect_fts_query_terms(sub, out);
}
@@ -36730,15 +36775,7 @@ fn query_node_to_fts_with_keyword_fields(
// become more permissive than the original query. Return
// None in that case so the caller falls back to stored-scan,
// which handles all child shapes correctly.
- //
- // `filter` children constrain the hit set exactly like `must`
- // (they differ only in scoring). They MUST NOT be dropped —
- // with keyword-field projections now producing real matches, a
- // dropped filter would silently overcount. Project them as
- // `must`, or fall back to the stored scan when one can't
- // project (unsupported Term/Range/etc. still project to None, so
- // classic filters keep taking the doc-scan path as before).
- for sub in must.iter().chain(filter.iter()) {
+ for sub in must {
let fq = query_node_to_fts_with_keyword_fields(
sub,
text_fields,
@@ -36748,6 +36785,29 @@ fn query_node_to_fts_with_keyword_fields(
bool_q = bool_q.must(fq);
projected_any = true;
}
+ // `filter` children constrain the hit set exactly like `must` but
+ // contribute NOTHING to `_score` (`BooleanClause.isScoring()` is
+ // `MUST || SHOULD` — BooleanClause.java:84-87). They MUST NOT be
+ // dropped — with keyword-field projections now producing real
+ // matches, a dropped filter would silently overcount — so they
+ // project onto the FTS bool's own non-scoring `filter` slot, or
+ // fall back to the stored scan when one can't project
+ // (unsupported Term/Range/etc. still project to None, so classic
+ // filters keep taking the doc-scan path as before).
+ //
+ // #361: these used to be projected as `must`, which made
+ // `bool{must:[text], filter:[term]}` score the filter's BM25 on
+ // top of the text clause and reorder the page.
+ for sub in filter {
+ let fq = query_node_to_fts_with_keyword_fields(
+ sub,
+ text_fields,
+ exact_fields,
+ keyword_fields,
+ )?;
+ bool_q = bool_q.filter(fq);
+ projected_any = true;
+ }
for sub in should {
// A `should` clause that can't be projected to FTS (e.g.
// MatchPhrase over indexed phrases) must NOT be silently
diff --git a/engine/crates/xerj-engine/tests/bool_filter_is_non_scoring.rs b/engine/crates/xerj-engine/tests/bool_filter_is_non_scoring.rs
new file mode 100644
index 000000000..3cab90fff
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/bool_filter_is_non_scoring.rs
@@ -0,0 +1,256 @@
+//! #361 — a `bool` clause that must not score, must not score.
+//!
+//! Two defects, one symptom. `bool.filter` was projected onto the FTS bool's
+//! `must` slot, so a filter's BM25 was SUMMED into `_score`; and the
+//! page-local "IDF-weighted rescore" then overwrote the exact BM25 the FTS
+//! path had produced whenever the bool had two or more Match/MultiMatch/Term
+//! children — counting `filter` and `must_not` among them — deriving its `N`
+//! from `final_hits.len()`, the RETURNED PAGE, which makes `_score` a
+//! function of `size`.
+//!
+//! Reference (apache/lucene, Apache-2.0, adapted not copied):
+//! * `BooleanClause.isScoring()` — `occur == MUST || occur == SHOULD`
+//! (BooleanClause.java:84-87): FILTER and MUST_NOT are non-scoring by
+//! definition.
+//! * `BooleanWeight`'s ctor builds each clause's Weight with
+//! `c.isScoring() ? scoreMode : ScoreMode.COMPLETE_NO_SCORES`
+//! (BooleanWeight.java:49-64) — a filter is structurally incapable of
+//! contributing a score.
+//! * `BM25Similarity.idfExplain` takes `N` from `fieldStats.docCount()`
+//! ("N, total number of documents with field", BM25Similarity.java:177-197)
+//! and `TermQuery.createWeight` gathers term statistics from
+//! `searcher.getTopReaderContext()` — the whole index
+//! (TermQuery.java:298-312). Never from the collected page.
+
+use std::collections::HashMap;
+
+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::executor::SearchResult;
+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(query: Value, size: usize) -> xerj_query::ast::SearchRequest {
+ parse_request(&json!({"query": query, "size": size})).expect("parse_request")
+}
+
+/// 120 docs over one `text` and one `keyword` field.
+///
+/// `alpha` is in every document with a varying term frequency (distinct BM25
+/// scores, so a rescore that collapses them is visible); `beta` is in the
+/// first 60 only (a different document frequency); `repo` splits the corpus
+/// in half so a keyword filter selects exactly 60. Flushed, because the bug
+/// is on the segment FTS path — the memtable scorer is a separate,
+/// deliberately-untouched population (see `heuristic_scored_applied`).
+async fn seed(name: &str) -> (TempDir, std::sync::Arc<Index>) {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let mut schema = Schema::empty();
+ schema
+ .fields
+ .push(FieldConfig::new("body", FieldType::Text));
+ schema
+ .fields
+ .push(FieldConfig::new("repo", FieldType::Keyword));
+ engine.create_index(name, schema).unwrap();
+ let idx = engine.get_index(name).unwrap();
+
+ for i in 0..120usize {
+ let alphas = "alpha ".repeat(1 + i % 5);
+ let betas = if i < 60 {
+ "beta ".repeat(1 + i % 3)
+ } else {
+ String::new()
+ };
+ let filler = "gamma ".repeat(1 + i % 7);
+ idx.index_document(
+ Some(format!("d{i:03}")),
+ json!({
+ "body": format!("{alphas}{betas}{filler}"),
+ "repo": if i % 2 == 0 { "lucene" } else { "usearch" },
+ }),
+ )
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+ (dir, idx)
+}
+
+fn score_map(result: &SearchResult) -> HashMap<String, f32> {
+ result
+ .hits
+ .iter()
+ .map(|h| (h.id.clone(), h.score))
+ .collect()
+}
+
+fn ids(result: &SearchResult) -> Vec<String> {
+ result.hits.iter().map(|h| h.id.clone()).collect()
+}
+
+/// Every hit's `_score` must equal the reference score for the same `_id`,
+/// and the order must be the reference order restricted to the returned set.
+fn assert_matches_reference(label: &str, reference: &SearchResult, actual: &SearchResult) {
+ let reference_scores = score_map(reference);
+ let reference_order = ids(reference);
+ for hit in &actual.hits {
+ let expected = reference_scores
+ .get(&hit.id)
+ .unwrap_or_else(|| panic!("{label}: {} is not in the reference result", hit.id));
+ assert!(
+ (hit.score - expected).abs() < 1e-4,
+ "{label}: _score for {} is {} but the same clause alone scores {expected}",
+ hit.id,
+ hit.score
+ );
+ }
+ let actual_ids = ids(actual);
+ let expected_order: Vec<String> = reference_order
+ .into_iter()
+ .filter(|id| actual_ids.contains(id))
+ .collect();
+ assert_eq!(
+ actual_ids, expected_order,
+ "{label}: hit order diverged from the unfiltered ranking"
+ );
+}
+
+const TEXT: &str = "alpha beta";
+
+fn text_query() -> Value {
+ json!({"match": {"body": TEXT}})
+}
+
+/// The headline of #361: `bool.must` + `bool.filter` — the most common query
+/// shape in the ES ecosystem — must score exactly like the `must` clause on
+/// its own. `BooleanClause.isScoring()` (BooleanClause.java:84-87).
+#[tokio::test]
+async fn filter_clause_contributes_nothing_to_score_or_order() {
+ let (_dir, idx) = seed("bool-filter-scoring").await;
+
+ // Reference: the text clause alone, deep enough to cover every hit the
+ // filtered queries can return.
+ let reference = idx.search(&req(text_query(), 200)).await.unwrap();
+ assert_eq!(reference.total.value, 120, "fixture: every doc has `alpha`");
+ let reference_scores = score_map(&reference);
+ assert!(
+ reference_scores.values().any(|s| *s > 1.0),
+ "fixture must expose the exact BM25 path, got {:?}",
+ reference.hits.first().map(|h| h.score)
+ );
+
+ // Wrapping in a bool changes nothing.
+ let wrapped = idx
+ .search(&req(json!({"bool": {"must": [text_query()]}}), 50))
+ .await
+ .unwrap();
+ assert_matches_reference("bool.must alone", &reference, &wrapped);
+
+ // Neither does adding a filter.
+ let filtered = idx
+ .search(&req(
+ json!({"bool": {
+ "must": [text_query()],
+ "filter": [{"term": {"repo": "lucene"}}]
+ }}),
+ 50,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(filtered.total.value, 60, "filter must still narrow the set");
+ assert_matches_reference("bool.must + bool.filter", &reference, &filtered);
+}
+
+/// `must_not` is non-scoring for the same reason as `filter`.
+#[tokio::test]
+async fn must_not_clause_contributes_nothing_to_score_or_order() {
+ let (_dir, idx) = seed("bool-must-not-scoring").await;
+ let reference = idx.search(&req(text_query(), 200)).await.unwrap();
+
+ let excluded = idx
+ .search(&req(
+ json!({"bool": {
+ "must": [text_query()],
+ "must_not": [{"term": {"repo": "usearch"}}]
+ }}),
+ 50,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(excluded.total.value, 60);
+ assert_matches_reference("bool.must + bool.must_not", &reference, &excluded);
+}
+
+/// The assertion that would have caught the defect, and that the earlier
+/// bool-scoring fix did not cover: BM25 statistics come from the index, not
+/// from the collected page (`TermQuery.createWeight` → `TermStates.build`
+/// over `searcher.getTopReaderContext()`, TermQuery.java:298-312), so
+/// `_score` cannot depend on `size`.
+///
+/// This shape has no filter at all — it is what `query_string` lowers to —
+/// and it is the half that the clause-walk fix alone does not reach.
+#[tokio::test]
+async fn score_is_invariant_to_page_size() {
+ let (_dir, idx) = seed("bool-size-invariance").await;
+
+ for query in [
+ json!({"bool": {"must": [
+ {"match": {"body": "alpha"}},
+ {"match": {"body": "beta"}}
+ ]}}),
+ json!({"bool": {"should": [
+ {"match": {"body": "alpha"}},
+ {"match": {"body": "beta"}}
+ ]}}),
+ json!({"bool": {
+ "must": [{"match": {"body": "alpha"}}],
+ "filter": [{"term": {"repo": "lucene"}}]
+ }}),
+ ] {
+ let deep = idx.search(&req(query.clone(), 50)).await.unwrap();
+ let shallow = idx.search(&req(query.clone(), 1)).await.unwrap();
+ assert!(!deep.hits.is_empty() && !shallow.hits.is_empty());
+ assert_eq!(
+ shallow.hits[0].id, deep.hits[0].id,
+ "{query}: size:1 and size:50 disagree on the best hit"
+ );
+ assert!(
+ (shallow.hits[0].score - deep.hits[0].score).abs() < 1e-4,
+ "{query}: top hit scores {} at size:1 but {} at size:50",
+ shallow.hits[0].score,
+ deep.hits[0].score
+ );
+ }
+}
+
+/// A bool whose only clauses are filters matches, and scores 0 — there is no
+/// scoring clause to sum. Green before this change; it must stay green.
+#[tokio::test]
+async fn filter_only_bool_still_scores_zero() {
+ let (_dir, idx) = seed("bool-filter-only").await;
+ let result = idx
+ .search(&req(
+ json!({"bool": {"filter": [{"term": {"repo": "lucene"}}]}}),
+ 50,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(result.total.value, 60);
+ assert_eq!(result.hits.len(), 50);
+ for hit in &result.hits {
+ assert_eq!(
+ hit.score, 0.0,
+ "{} scored {} on a filter-only bool",
+ hit.id, hit.score
+ );
+ }
+}
diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rs
index 1ad15d53f..15001d454 100644
--- a/engine/crates/xerj-fts/src/search.rs
+++ b/engine/crates/xerj-fts/src/search.rs
@@ -6,7 +6,7 @@
//! |-------------|--------------------------------------------------|
//! | `TermQuery` | Single-term lookup: FST → postings → BM25 score |
//! | `PhraseQuery`| Ordered adjacent term positions in same document |
-//! | `BoolQuery` | must / should / must_not combinator |
+//! | `BoolQuery` | must / should / must_not / filter combinator |
//! | `PrefixQuery`| FST range scan for all terms with a given prefix |
//!
//! ## Parallelism
@@ -353,6 +353,16 @@ pub struct BoolQuery {
/// No must_not clause must match.
#[serde(default)]
pub must_not: Vec<Query>,
+ /// All filter clauses must match, but they contribute NOTHING to
+ /// `_score` — the same split Lucene draws in `BooleanClause.isScoring()`
+ /// (`occur == MUST || occur == SHOULD`, BooleanClause.java:84-87) and
+ /// enforces structurally in `BooleanWeight`'s ctor by building a FILTER
+ /// clause's `Weight` with `ScoreMode.COMPLETE_NO_SCORES`
+ /// (BooleanWeight.java:49-64). Projecting a `filter` child as `must`
+ /// instead (what this crate's caller used to do) makes the clause
+ /// scoring, which is #361.
+ #[serde(default)]
+ pub filter: Vec<Query>,
/// Minimum number of `should` clauses that must match (default = 1 when
/// there are no `must` clauses, 0 otherwise — same as ES).
pub min_should_match: Option<u32>,
@@ -371,6 +381,7 @@ impl Default for BoolQuery {
must: Vec::new(),
should: Vec::new(),
must_not: Vec::new(),
+ filter: Vec::new(),
min_should_match: None,
boost: 1.0,
}
@@ -1084,16 +1095,21 @@ impl FtsSearcher {
// ── Bool query ────────────────────────────────────────────────────────────
fn execute_bool(&self, bq: &BoolQuery, explain: bool) -> Result<Vec<ScoredHit>> {
- // Determine effective min_should_match
- let min_should = bq.min_should_match.unwrap_or(if bq.must.is_empty() {
- if bq.should.is_empty() {
- 0
- } else {
- 1
- }
- } else {
- 0
- });
+ // Determine effective min_should_match. `filter` counts as a
+ // required clause here exactly like `must` — ES defaults the minimum
+ // to 1 only when the bool has should clauses and NO must/filter
+ // clause — so a `bool{filter, should}` keeps optional shoulds.
+ let min_should =
+ bq.min_should_match
+ .unwrap_or(if bq.must.is_empty() && bq.filter.is_empty() {
+ if bq.should.is_empty() {
+ 0
+ } else {
+ 1
+ }
+ } else {
+ 0
+ });
// Execute all sub-queries.
//
@@ -1134,6 +1150,11 @@ impl FtsSearcher {
let Some(must_hits) = run_clauses(&bq.must, false)? else {
return Ok(Vec::new());
};
+ // `filter` narrows exactly like `must` (partial_ok = false for the
+ // same reason: dropping one would RELAX the query).
+ let Some(filter_hits) = run_clauses(&bq.filter, false)? else {
+ return Ok(Vec::new());
+ };
let Some(should_hits) = run_clauses(&bq.should, true)? else {
return Ok(Vec::new());
};
@@ -1163,6 +1184,21 @@ impl FtsSearcher {
}
}
+ // Intersect filter clauses — membership ONLY. Lucene builds a FILTER
+ // clause's Weight with `ScoreMode.COMPLETE_NO_SCORES`
+ // (BooleanWeight.java:49-64, gated on `BooleanClause.isScoring()` at
+ // BooleanClause.java:84-87), so a filter is structurally incapable of
+ // contributing to the score; there is nothing to add and then
+ // subtract. Deliberately no `score_map` update below (#361).
+ for filter_result in &filter_hits {
+ let doc_set: std::collections::HashSet<u32> =
+ filter_result.iter().map(|h| h.doc_id).collect();
+ candidate_docs = Some(match candidate_docs {
+ None => doc_set,
+ Some(prev) => prev.intersection(&doc_set).copied().collect(),
+ });
+ }
+
// Should clauses: track per-doc match count and scores
let mut should_match_count: std::collections::HashMap<u32, u32> =
std::collections::HashMap::new();
@@ -1173,8 +1209,9 @@ impl FtsSearcher {
}
}
- // If no must clauses, candidate set is the union of should docs
- if bq.must.is_empty() {
+ // If no REQUIRED clauses at all (must ∪ filter), the candidate set is
+ // the union of should docs.
+ if bq.must.is_empty() && bq.filter.is_empty() {
candidate_docs = Some(should_match_count.keys().copied().collect());
}
@@ -1494,6 +1531,12 @@ impl BoolQuery {
self
}
+ /// Required, but non-scoring — see the `filter` field's note.
+ pub fn filter(mut self, q: Query) -> Self {
+ self.filter.push(q);
+ self
+ }
+
pub fn min_should_match(mut self, n: u32) -> Self {
self.min_should_match = Some(n);
self
@@ -1774,6 +1817,75 @@ mod tests {
);
}
+ /// #361 — a `filter` clause narrows exactly like a second `must`, and
+ /// contributes exactly nothing to `_score`. Lucene builds a FILTER
+ /// clause's Weight with `ScoreMode.COMPLETE_NO_SCORES`
+ /// (BooleanWeight.java:49-64, gated on `BooleanClause.isScoring()` at
+ /// BooleanClause.java:84-87).
+ #[test]
+ fn bool_query_filter_narrows_without_scoring() {
+ let dir = TempDir::new().unwrap();
+ let searcher = setup_searcher(dir.path());
+
+ let fox = || Query::Term(TermQuery::new("body", "fox"));
+ let quick = || Query::Term(TermQuery::new("body", "quick"));
+
+ let bare = searcher
+ .search(
+ &Query::Bool(Box::new(BoolQuery::new().must(fox()))),
+ 10,
+ false,
+ )
+ .unwrap();
+ let bare_scores: HashMap<u32, f32> = bare.iter().map(|h| (h.doc_id, h.score)).collect();
+
+ let filtered = searcher
+ .search(
+ &Query::Bool(Box::new(BoolQuery::new().must(fox()).filter(quick()))),
+ 10,
+ false,
+ )
+ .unwrap();
+ let conjunction = searcher
+ .search(
+ &Query::Bool(Box::new(BoolQuery::new().must(fox()).must(quick()))),
+ 10,
+ false,
+ )
+ .unwrap();
+
+ // Same membership as the two-`must` conjunction …
+ let mut filtered_ids: Vec<u32> = filtered.iter().map(|h| h.doc_id).collect();
+ let mut conjunction_ids: Vec<u32> = conjunction.iter().map(|h| h.doc_id).collect();
+ filtered_ids.sort_unstable();
+ conjunction_ids.sort_unstable();
+ assert_eq!(
+ filtered_ids, conjunction_ids,
+ "filter must narrow like must"
+ );
+ assert!(!filtered_ids.is_empty(), "fixture: docs 0 and 1 match both");
+
+ // … the `fox` score unchanged …
+ for hit in &filtered {
+ let bare_score = bare_scores[&hit.doc_id];
+ assert!(
+ (hit.score - bare_score).abs() < 1e-6,
+ "doc {} scored {} with a filter but {bare_score} without it",
+ hit.doc_id,
+ hit.score
+ );
+ }
+ // … and the same clause as a `must` DOES add its BM25, which is the
+ // behaviour the projection used to give every `bool.filter`.
+ for hit in &conjunction {
+ assert!(
+ hit.score > bare_scores[&hit.doc_id],
+ "doc {} did not gain score from a scoring `must` clause",
+ hit.doc_id
+ );
+ }
+ }
+
#[test]
fn bool_query_must_not_excludes() {
let dir = TempDir::new().unwrap();