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(code): semantic mode queries each index's embedded field (#1621)
xerj-org91af5895619c
diff --git a/engine/crates/xerj-common/src/xccode/fields.rs b/engine/crates/xerj-common/src/xccode/fields.rsindex d42d3f640..0ba690e47 100644--- a/engine/crates/xerj-common/src/xccode/fields.rs+++ b/engine/crates/xerj-common/src/xccode/fields.rs@@ -369,6 +369,72 @@ pub fn semantic_capable(mapping: Option<&Value>) -> (Vec<String>, usize) {(capable, mapping.len())}+/// One semantic field per index, then indices grouped by that field.+///+/// Preference is `body`, then `text`, then the alphabetically first+/// `semantic_text` property. Code indices often elect `code` (or prose+/// elects `text`) while a document dataset elects `body`; a query that only+/// names `body` never reaches the others, and posting `body` at an index+/// that maps it as plain `text` 400s the whole request.+///+/// Groups are ordered `body`, `text`, then the remaining field names.+/// Index names inside a group are sorted. An unreadable mapping is empty.+pub fn semantic_groups(mapping: Option<&Value>) -> (Vec<(String, Vec<String>)>, usize) {+ let Some(mapping) = mapping.and_then(Value::as_object) else {+ return (Vec::new(), 0);+ };+ let mut by_field: std::collections::BTreeMap<String, Vec<String>> =+ std::collections::BTreeMap::new();+ for (name, body) in mapping {+ let Some(chosen) = elected_semantic_field(body) else {+ continue;+ };+ by_field.entry(chosen).or_default().push(name.clone());+ }+ let mut groups: Vec<(String, Vec<String>)> = by_field.into_iter().collect();+ for (_, indices) in &mut groups {+ indices.sort();+ }+ groups.sort_by(|left, right| {+ semantic_field_rank(&left.0)+ .cmp(&semantic_field_rank(&right.0))+ .then_with(|| left.0.cmp(&right.0))+ });+ (groups, mapping.len())+}++fn semantic_field_rank(field: &str) -> u8 {+ match field {+ "body" => 0,+ "text" => 1,+ _ => 2,+ }+}++fn elected_semantic_field(mapping_body: &Value) -> Option<String> {+ let props = mapping_body+ .pointer("/mappings/properties")+ .and_then(Value::as_object)?;+ let mut semantic: Vec<&str> = props+ .iter()+ .filter(|(_, spec)| {+ spec.get("type")+ .and_then(Value::as_str)+ .is_some_and(|ty| ty == "semantic_text")+ })+ .map(|(name, _)| name.as_str())+ .collect();+ if semantic.is_empty() {+ return None;+ }+ semantic.sort_unstable();+ let chosen = ["body", "text"]+ .into_iter()+ .find(|preferred| semantic.contains(preferred))+ .unwrap_or(semantic[0]);+ Some(chosen.to_string())+}+#[cfg(test)]mod tests {use super::*;@@ -459,6 +525,48 @@ mod tests {assert!(semantic_capable(None) == (Vec::new(), 0));}+ /// A code index that elects `code` (not `body`) and a prose index that+ /// elects `text` must both be queried, on their own field. `body` wins+ /// when an index maps both.+ #[test]+ fn semantic_groups_follow_the_field_each_index_actually_embeds() {+ let m = json!({+ "manifest": { "mappings": { "properties": {+ "body": { "type": "semantic_text" },+ "text": { "type": "text" }+ }}},+ "code": { "mappings": { "properties": {+ "body": { "type": "text" },+ "code": { "type": "semantic_text" }+ }}},+ "prose": { "mappings": { "properties": {+ "text": { "type": "semantic_text" },+ "title": { "type": "text" }+ }}},+ "both": { "mappings": { "properties": {+ "body": { "type": "semantic_text" },+ "text": { "type": "semantic_text" }+ }}},+ "plain": { "mappings": { "properties": {+ "body": { "type": "text" }+ }}}+ });+ let (groups, total) = semantic_groups(Some(&m));+ assert_eq!(total, 5);+ assert_eq!(+ groups,+ vec![+ (+ "body".to_string(),+ vec!["both".to_string(), "manifest".to_string()]+ ),+ ("text".to_string(), vec!["prose".to_string()]),+ ("code".to_string(), vec!["code".to_string()]),+ ]+ );+ assert!(semantic_groups(None).0.is_empty());+ }+/// #1158: a raw-JSON corpus (ghsa-db advisories) maps none of the/// standard content fields — the old `["body"]` floor was a field no/// index maps, and an unmapped multi_match field collapses adiff --git a/engine/crates/xerj-common/src/xccode/mod.rs b/engine/crates/xerj-common/src/xccode/mod.rsindex f403e939f..8fb771d34 100644--- a/engine/crates/xerj-common/src/xccode/mod.rs+++ b/engine/crates/xerj-common/src/xccode/mod.rs@@ -327,27 +327,46 @@ pub fn run_code_query()}};- let (capable, total) = fields::semantic_capable(Some(&mapping));- if capable.is_empty() {+ // Group by the field each index actually embeds. One request+ // cannot name two semantic fields, and naming `body` at an index+ // whose embedded field is `code` or `text` 400s every index in+ // the comma-join.+ let (groups, total) = fields::semantic_groups(Some(&mapping));+ if groups.is_empty() {// No semantic arm is possible: do NOT post the query. An// empty comma-join is an empty index segment, which the// server reads as `/_search` — every index on the node,// corpus or not. The empty answer with its note is the// honest result.note = Some(format!(- "no index under '{pattern}' maps `body` as semantic_text"+ "no index under '{pattern}' maps a field as semantic_text"));(Value::Null, Vec::new())} else {+ let indexed: usize = groups.iter().map(|(_, names)| names.len()).sum();+ let described = groups+ .iter()+ .map(|(field, names)| format!("{field} ({})", names.len()))+ .collect::<Vec<_>>()+ .join(", ");note = Some(format!(- "vector only over {} of {total} index(es)",- capable.len()+ "vector only over {indexed} of {total} index(es): {described}"));- let body = semantic_body(&query, fetch, ¶ms.lang);- match http.search(&capable.join(","), &body) {- Ok(r) => (r.clone(), hit_list(&r)),- Err(e) => return CodeOutcome::refused(format!("search failed: {e}"), 2),+ let mut merged: Option<Value> = None;+ for (field, names) in &groups {+ let body = semantic_on_field(field, &query, fetch, ¶ms.lang);+ match http.search(&names.join(","), &body) {+ Ok(response) => {+ merged = Some(match merged {+ Some(prev) => merge_by_score(prev, &response, fetch),+ None => response,+ });+ }+ Err(e) => return CodeOutcome::refused(format!("search failed: {e}"), 2),+ }}+ let response = merged.unwrap_or(Value::Null);+ (response.clone(), hit_list(&response))}}Mode::Hybrid => {@@ -976,13 +995,20 @@ pub(crate) fn fuse_file_and_symbol_hits(out}-/// The vector-only body. Aimed ONLY at indices whose `body` is semantic_text-/// (a semantic query against plain text 400s the whole wildcard).+/// The vector-only body aimed at `field`. A semantic query against a plain+/// `text` field 400s the whole request, so callers pass only indices that+/// embed this field. Hybrid still hardcodes `body`; semantic mode passes+/// the field [`fields::semantic_groups`] elected.////// The clause carries `k` = the fetch window: without it the parser cuts the/// vector pool to 10 whatever `size` says (#1145).-pub(crate) fn semantic_body(query: &str, k: usize, lang: &Option<String>) -> Value {- let q = serde_json::json!({ "semantic": { "field": "body", "query": query, "k": k } });+pub(crate) fn semantic_on_field(+ field: &str,+ query: &str,+ k: usize,+ lang: &Option<String>,+) -> Value {+ let q = serde_json::json!({ "semantic": { "field": field, "query": query, "k": k } });// `--lang` rides in `filter`: the engine sends a bool to the vector path// only when the semantic clause is its sole must/should clause (#1148).let query = match lang {@@ -1669,7 +1695,16 @@ mod tests {/// vector@10 (the #1137 overfetch widened the BM25 leg alone).#[test]fn the_vector_leg_carries_the_fetch_window_as_k() {- let sem = semantic_body("q", 50, &None);+ let sem = semantic_on_field("body", "q", 50, &None);+ assert_eq!(+ sem.pointer("/query/semantic/field"),+ Some(&serde_json::json!("body"))+ );+ let on_code = semantic_on_field("code", "q", 50, &None);+ assert_eq!(+ on_code.pointer("/query/semantic/field"),+ Some(&serde_json::json!("code"))+ );assert_eq!(sem.pointer("/size"), Some(&serde_json::json!(50)));assert_eq!(sem.pointer("/query/semantic/k"),@@ -1695,7 +1730,7 @@ mod tests {let lang = Some("rust".to_string());let want_filter = serde_json::json!([{ "match": { "language": "rust" } }]);- let sem = semantic_body("q", 50, &lang);+ let sem = semantic_on_field("body", "q", 50, &lang);let must = sem.pointer("/query/bool/must").and_then(Value::as_array);assert_eq!(must.map(Vec::len), Some(1), "{sem}");assert!(must.unwrap()[0].get("semantic").is_some(), "{sem}");