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(sort): reduce multi-valued field to min/max representative (#826) (#827)
xerj-org59a745c99f11
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 5feb3de5b..9e7c378d9 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -1766,6 +1766,69 @@ mod flush_publication_recovery_tests {assert_eq!(got["extra"], json!(1), "new top-level key added: {got}");}+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn multivalue_sort_reduces_min_for_asc_max_for_desc() {+ // A multi-valued numeric field must rank by each doc's MIN value for an+ // ascending sort and MAX for a descending one (ES default), with an+ // explicit `mode` overriding that. Before the fix, `compute_sort_values`+ // handed the raw array to the comparator, which fell through to+ // `stringify-and-compare` — ranking docs by the JSON text of the array.+ let _fault_test = FLUSH_FAULT_TEST_LOCK.lock().await;+ let dir = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ let engine = crate::Engine::new(config).unwrap();+ engine.create_index("mvs", Schema::empty()).unwrap();+ let idx = engine.get_index("mvs").unwrap();+ idx.abort_background_tasks();+ // mins: A=1 C=5 B=40 maxes: C=100 B=50 A=10+ idx.index_document(Some("A".into()), json!({"vals": [10, 1]}))+ .await+ .unwrap();+ idx.index_document(Some("B".into()), json!({"vals": [40, 50]}))+ .await+ .unwrap();+ idx.index_document(Some("C".into()), json!({"vals": [5, 100]}))+ .await+ .unwrap();+ // A single-element array must sort numerically, not lexically:+ // string compare put "[10]" before "[9]".+ idx.index_document(Some("nine".into()), json!({"v1": [9]}))+ .await+ .unwrap();+ idx.index_document(Some("ten".into()), json!({"v1": [10]}))+ .await+ .unwrap();+ let order = |idx: std::sync::Arc<crate::Index>, body: serde_json::Value| async move {+ let req = xerj_query::parse_request(&body).unwrap();+ let r = idx.search(&req).await.unwrap();+ r.hits.iter().map(|h| h.id.clone()).collect::<Vec<_>>()+ };+ let asc = json!({"query":{"exists":{"field":"vals"}},"size":10,"sort":[{"vals":{"order":"asc"}}]});+ let desc = json!({"query":{"exists":{"field":"vals"}},"size":10,"sort":[{"vals":{"order":"desc"}}]});+ let asc_max = json!({"query":{"exists":{"field":"vals"}},"size":10,"sort":[{"vals":{"order":"asc","mode":"max"}}]});+ let single =+ json!({"query":{"exists":{"field":"v1"}},"size":10,"sort":[{"v1":{"order":"asc"}}]});+ let check = |idx: &std::sync::Arc<crate::Index>| {+ let idx = idx.clone();+ let (asc, desc, asc_max, single) =+ (asc.clone(), desc.clone(), asc_max.clone(), single.clone());+ async move {+ // asc -> by min: A(1) C(5) B(40)+ assert_eq!(order(idx.clone(), asc).await, vec!["A", "C", "B"]);+ // desc -> by max: C(100) B(50) A(10)+ assert_eq!(order(idx.clone(), desc).await, vec!["C", "B", "A"]);+ // explicit mode:max overrides the asc default: A(10) B(50) C(100)+ assert_eq!(order(idx.clone(), asc_max).await, vec!["A", "B", "C"]);+ // single-element arrays sort numerically: 9 before 10+ assert_eq!(order(idx.clone(), single).await, vec!["nine", "ten"]);+ }+ };+ check(&idx).await;+ idx.flush().await.unwrap();+ check(&idx).await;+ }+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn mustnot_only_prefix_keeps_nonmatching_docs_after_flush() {// #797: a bool with ONLY a must_not (no must/should/filter) containing a@@ -41142,6 +41205,13 @@ fn compute_sort_values(get_field_value(source, base)}).unwrap_or(Value::Null);+ // A multi-valued field is reduced to its single representative+ // value FIRST (ES: `min` for asc / `max` for desc unless an+ // explicit `mode` overrides), so the comparator never sees a raw+ // array. Without this the two arrays fell through to+ // `compare_values`' stringify-and-compare fallback, ranking+ // multi-valued docs by the JSON text of the array (`[9]` > `[10]`).+ let raw = xerj_query::sort::reduce_sort_value(&raw, sf.order, sf.mode);match raw {Value::String(ref s) if looks_like_date(s) => {date_string_to_epoch(s).unwrap_or(raw)diff --git a/engine/crates/xerj-query/src/sort.rs b/engine/crates/xerj-query/src/sort.rsindex 2193482d2..5e9728fa4 100644--- a/engine/crates/xerj-query/src/sort.rs+++ b/engine/crates/xerj-query/src/sort.rs@@ -116,10 +116,15 @@ impl SortOrder {#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]#[serde(rename_all = "lowercase")]pub enum SortMode {+ /// No explicit `mode` was requested. ES then picks the `min` value for an+ /// ascending sort and the `max` value for a descending one — see+ /// `effective(order)`. Kept distinct from an explicit `min`/`max` so that+ /// `{"order":"desc"}` (no mode) resolves to `max`, not the enum default.+ #[default]+ Default,/// Use the minimum value across all field values.Min,- /// Use the maximum value across all field values (default for `asc`).- #[default]+ /// Use the maximum value across all field values.Max,/// Use the arithmetic mean.Avg,@@ -129,6 +134,85 @@ pub enum SortMode {Median,}+impl SortMode {+ /// Resolve the effective reduction for a multi-valued field, applying ES's+ /// order-based default (`asc` -> min, `desc` -> max) when no explicit mode+ /// was given. An explicit mode is honoured regardless of order.+ pub fn effective(self, order: SortOrder) -> SortMode {+ match self {+ SortMode::Default => match order {+ SortOrder::Asc => SortMode::Min,+ SortOrder::Desc => SortMode::Max,+ },+ other => other,+ }+ }+}++/// Reduce a (possibly multi-valued) sort field value to the single+/// representative value ES would compare, per the sort `mode` and `order`.+///+/// A non-array value is returned unchanged. `null` array entries are ignored+/// (ES skips them when selecting the representative); an array that is empty or+/// all-null reduces to `Null`, so the request's `missing` policy governs it.+/// `min`/`max` use the same numbers-then-strings ordering as the sort+/// comparator; `avg`/`sum`/`median` are numeric-only (non-numeric entries are+/// ignored, matching ES, which rejects them at mapping time).+pub fn reduce_sort_value(+ raw: &serde_json::Value,+ order: SortOrder,+ mode: SortMode,+) -> serde_json::Value {+ use serde_json::Value;+ let arr = match raw {+ Value::Array(a) => a,+ other => return other.clone(),+ };+ let vals: Vec<&Value> = arr.iter().filter(|v| !v.is_null()).collect();+ if vals.is_empty() {+ return Value::Null;+ }+ match mode.effective(order) {+ SortMode::Min => vals+ .iter()+ .copied()+ .min_by(|a, b| compare_values(a, b, &SortMissing::Last))+ .cloned()+ .unwrap_or(Value::Null),+ SortMode::Max => vals+ .iter()+ .copied()+ .max_by(|a, b| compare_values(a, b, &SortMissing::Last))+ .cloned()+ .unwrap_or(Value::Null),+ SortMode::Avg | SortMode::Sum | SortMode::Median => {+ let mut nums: Vec<f64> = vals.iter().filter_map(|v| v.as_f64()).collect();+ if nums.is_empty() {+ return Value::Null;+ }+ let out = match mode.effective(order) {+ SortMode::Sum => nums.iter().sum(),+ SortMode::Avg => nums.iter().sum::<f64>() / nums.len() as f64,+ SortMode::Median => {+ nums.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ let m = nums.len() / 2;+ if nums.len() % 2 == 1 {+ nums[m]+ } else {+ (nums[m - 1] + nums[m]) / 2.0+ }+ }+ _ => unreachable!(),+ };+ serde_json::Number::from_f64(out)+ .map(Value::Number)+ .unwrap_or(Value::Null)+ }+ // `effective` never returns `Default`.+ SortMode::Default => Value::Null,+ }+}+// ─────────────────────────────────────────────────────────────────────────────// SortMissing// ─────────────────────────────────────────────────────────────────────────────