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(highlight): expand field-name patterns in highlight.fields (#1281)
Vincenzo Lombardo0ca92fab4685
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 767a40351..7968379be 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -6961,6 +6961,7 @@ fn parse_highlight(hl_val: &Value) -> Option<xerj_query::ast::HighlightRequest>.get("number_of_fragments").and_then(Value::as_u64).map(|n| n as usize),+ require_field_match: obj.get("require_field_match").and_then(Value::as_bool),})}diff --git a/engine/crates/xerj-api/tests/highlight_field_patterns.rs b/engine/crates/xerj-api/tests/highlight_field_patterns.rsnew file mode 100644index 000000000..767ee8279--- /dev/null+++ b/engine/crates/xerj-api/tests/highlight_field_patterns.rs@@ -0,0 +1,198 @@+//! Issue #1281: field names in `highlight.fields` may be patterns (`"*"`,+//! `"mess*"`, `"obj.*"`). XERJ looked each key up as a literal `_source` key,+//! so a Kibana-Discover-style `"fields": {"*": {}}` returned no highlight at+//! all. Expected results below were each verified against ES 8.13.4 on the+//! same mapping and document.+//!+//! Elasticsearch is referenced for wire semantics only; no ES code is+//! reproduced here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++async fn app() -> (axum::Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap(),+ )+ .await+ .unwrap();+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++async fn seeded() -> (axum::Router, tempfile::TempDir) {+ let (app, dir) = app().await;+ let (st, body) = call(+ &app,+ "PUT",+ "/hl",+ json!({"mappings": {"properties": {+ "message": {"type": "text"},+ "title": {"type": "text"},+ "host": {"type": "keyword"},+ "n": {"type": "long"},+ "obj": {"properties": {"inner": {"type": "text"}}}+ }}}),+ )+ .await;+ assert_eq!(st, StatusCode::OK, "create index: {body}");+ let (st, body) = call(+ &app,+ "PUT",+ "/hl/_doc/1?refresh=true",+ json!({+ "message": "upstream timeout contacting backend",+ "title": "timeout report",+ "host": "timeout",+ "n": 5,+ "obj": {"inner": "a timeout here"}+ }),+ )+ .await;+ assert_eq!(st, StatusCode::CREATED, "index doc: {body}");+ (app, dir)+}++/// The highlighted field names of the first hit, sorted.+async fn highlighted(app: &axum::Router, body: Value) -> Vec<String> {+ let (st, resp) = call(app, "POST", "/hl/_search", body.clone()).await;+ assert_eq!(st, StatusCode::OK, "{body}: {resp}");+ let mut names: Vec<String> = resp["hits"]["hits"][0]["highlight"]+ .as_object()+ .map(|o| o.keys().cloned().collect())+ .unwrap_or_default();+ names.sort();+ names+}++#[tokio::test]+async fn star_highlights_the_queried_field() {+ let (app, _dir) = seeded().await;+ let body = json!({+ "_source": false,+ "query": {"match": {"message": "timeout"}},+ "highlight": {"fields": {"*": {}}}+ });+ let (st, resp) = call(&app, "POST", "/hl/_search", body).await;+ assert_eq!(st, StatusCode::OK, "{resp}");+ assert_eq!(+ resp["hits"]["hits"][0]["highlight"],+ json!({"message": ["upstream <em>timeout</em> contacting backend"]}),+ "{resp}"+ );+ for pattern in ["mess*", "*age", "m*e"] {+ let names = highlighted(+ &app,+ json!({+ "query": {"match": {"message": "timeout"}},+ "highlight": {"fields": {pattern: {}}}+ }),+ )+ .await;+ assert_eq!(names, ["message"], "{pattern}");+ }+}++#[tokio::test]+async fn require_field_match_false_highlights_every_text_and_keyword_field() {+ let (app, _dir) = seeded().await;+ let names = highlighted(+ &app,+ json!({+ "query": {"match": {"message": "timeout"}},+ "highlight": {"require_field_match": false, "fields": {"*": {}}}+ }),+ )+ .await;+ // `n` (long) is never a highlight target.+ assert_eq!(names, ["host", "message", "obj.inner", "title"]);++ let names = highlighted(+ &app,+ json!({+ "query": {"match": {"message": "timeout"}},+ "highlight": {"require_field_match": false, "fields": {"t*": {}}}+ }),+ )+ .await;+ assert_eq!(names, ["title"]);+}++#[tokio::test]+async fn star_follows_the_fields_the_query_targets() {+ let (app, _dir) = seeded().await;+ for (query, expected) in [+ (+ json!({"multi_match": {"query": "timeout", "fields": ["message", "title"]}}),+ vec!["message", "title"],+ ),+ (+ json!({"query_string": {"query": "timeout"}}),+ vec!["host", "message", "obj.inner", "title"],+ ),+ (json!({"term": {"host": "timeout"}}), vec!["host"]),+ ] {+ let names = highlighted(+ &app,+ json!({"query": query, "highlight": {"fields": {"*": {}}}}),+ )+ .await;+ assert_eq!(names, expected, "{query}");+ }+ let names = highlighted(+ &app,+ json!({+ "query": {"match": {"obj.inner": "timeout"}},+ "highlight": {"fields": {"obj.*": {}}}+ }),+ )+ .await;+ assert_eq!(names, ["obj.inner"]);+}++#[tokio::test]+async fn pattern_options_apply_to_each_expanded_field() {+ let (app, _dir) = seeded().await;+ let (st, resp) = call(+ &app,+ "POST",+ "/hl/_search",+ json!({+ "query": {"match": {"message": "timeout"}},+ "highlight": {"fields": {"mess*": {"pre_tags": ["<b>"], "post_tags": ["</b>"]}}}+ }),+ )+ .await;+ assert_eq!(st, StatusCode::OK, "{resp}");+ assert_eq!(+ resp["hits"]["hits"][0]["highlight"],+ json!({"message": ["upstream <b>timeout</b> contacting backend"]}),+ "{resp}"+ );+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex a61f96e5b..b5d1111ec 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -24954,7 +24954,16 @@ impl Index {// body for a 160-byte answer. That matters most to the callers most// likely to use highlighting — agents paying per token for context.let page = if let Some(hl_req) = &request.highlight {- apply_highlight(page, hl_req, query)+ // #1281: field names may be patterns (`"*"`, `"mess*"`), which+ // `apply_highlight` would otherwise look up as literal source keys+ // and never find.+ if hl_req.fields.keys().any(|f| f.contains('*')) {+ let schema = self.schema.read().await;+ let expanded = expand_highlight_field_patterns(hl_req, &schema.schema, query);+ apply_highlight(page, &expanded, query)+ } else {+ apply_highlight(page, hl_req, query)+ }} else {page};@@ -36118,6 +36127,127 @@ fn apply_highlight(hits: Vec<Hit>, hl: &HighlightRequest, query: &QueryNode) ->.collect()}+/// Expand field-name patterns in a highlight request against the mapping+/// (#1281).+///+/// ES 8.13.4 (verified) expands a pattern to the mapped `text` and `keyword`+/// fields it matches, object sub-fields included (`obj.*` → `obj.inner`) and+/// numeric fields excluded. With `require_field_match` (default `true`) only+/// the fields the query targets survive: `match: {message}` + `"*"` highlights+/// `message` alone, while a field-less `query_string` highlights them all. An+/// explicit entry is kept as written and wins over a pattern that also covers+/// it; the pattern's options are copied to each field it expands to.+fn expand_highlight_field_patterns(+ hl: &HighlightRequest,+ schema: &Schema,+ query: &QueryNode,+) -> HighlightRequest {+ fn highlightable(fields: &[FieldConfig], prefix: &str, out: &mut Vec<String>) {+ for fc in fields {+ let path = if prefix.is_empty() {+ fc.name.clone()+ } else {+ format!("{prefix}.{}", fc.name)+ };+ match fc.field_type {+ FieldType::Text | FieldType::Keyword => out.push(path),+ // Object properties are fields of their own; a text field's+ // `fields` are multi-fields, which this expansion skips.+ FieldType::Object | FieldType::Nested => highlightable(&fc.fields, &path, out),+ _ => {}+ }+ }+ }+ fn glob(pattern: &str, name: &str) -> bool {+ let parts: Vec<&str> = pattern.split('*').collect();+ let (first, last) = (parts[0], parts[parts.len() - 1]);+ if !name.starts_with(first) || name.len() < first.len() + last.len() {+ return false;+ }+ let mut rest = &name[first.len()..];+ for mid in &parts[1..parts.len() - 1] {+ match rest.find(mid) {+ Some(at) => rest = &rest[at + mid.len()..],+ None => return false,+ }+ }+ rest.ends_with(last)+ }+ // Collects the field names (possibly patterns: a field-less+ // `query_string` reaches here as `match` on `"*"`) the query targets.+ // Returns `false` when the query targets every field outright.+ fn spec(f: &str, out: &mut Vec<String>) -> bool {+ out.push(f.split('^').next().unwrap_or(f).to_string());+ true+ }+ fn targeted(q: &QueryNode, out: &mut Vec<String>) -> bool {+ match q {+ QueryNode::Term { field, .. }+ | QueryNode::Terms { field, .. }+ | QueryNode::Range { field, .. }+ | QueryNode::Prefix { field, .. }+ | QueryNode::Wildcard { field, .. }+ | QueryNode::Match { field, .. }+ | QueryNode::MatchPhrase { field, .. }+ | QueryNode::MatchPhrasePrefix { field, .. }+ | QueryNode::Fuzzy { field, .. }+ | QueryNode::Regexp { field, .. } => {+ out.push(field.clone());+ true+ }+ QueryNode::MultiMatch { fields, .. } | QueryNode::SimpleQueryString { fields, .. } => {+ if fields.is_empty() {+ return false;+ }+ fields.iter().all(|f| spec(f, out))+ }+ QueryNode::QueryString { default_field, .. } => match default_field {+ Some(f) => spec(f, out),+ None => false,+ },+ QueryNode::Bool {+ must,+ should,+ must_not,+ filter,+ ..+ } => must+ .iter()+ .chain(should)+ .chain(must_not)+ .chain(filter)+ .all(|c| targeted(c, out)),+ QueryNode::Constant { query, .. }+ | QueryNode::Boosted { query, .. }+ | QueryNode::Named { query, .. }+ | QueryNode::Nested { query, .. }+ | QueryNode::FunctionScore { query, .. } => targeted(query, out),+ QueryNode::DisMax { queries, .. } => queries.iter().all(|c| targeted(c, out)),+ _ => true,+ }+ }++ let mut candidates = Vec::new();+ highlightable(&schema.fields, "", &mut candidates);+ if hl.require_field_match != Some(false) {+ let mut named = Vec::new();+ if targeted(query, &mut named) {+ candidates.retain(|c| named.iter().any(|n| n == c || glob(n, c)));+ }+ }++ let mut out = hl.clone();+ out.fields.retain(|name, _| !name.contains('*'));+ for (pattern, opts) in hl.fields.iter().filter(|(name, _)| name.contains('*')) {+ for field in candidates.iter().filter(|c| glob(pattern, c)) {+ out.fields+ .entry(field.clone())+ .or_insert_with(|| opts.clone());+ }+ }+ out+}+/// Extract query terms for highlighting.////// Returns lowercase tokens that should be highlighted.diff --git a/engine/crates/xerj-query/src/ast.rs b/engine/crates/xerj-query/src/ast.rsindex 3c48aea56..61a1543ee 100644--- a/engine/crates/xerj-query/src/ast.rs+++ b/engine/crates/xerj-query/src/ast.rs@@ -1383,6 +1383,12 @@ pub struct HighlightRequest {/// Number of fragments to return per field (default 5).#[serde(default, skip_serializing_if = "Option::is_none")]pub number_of_fragments: Option<usize>,++ /// ES `require_field_match` (default `true`): when a field PATTERN such+ /// as `"*"` is expanded, keep only the fields the query actually targets.+ /// `false` keeps every matching text/keyword field.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub require_field_match: Option<bool>,}/// Per-field highlight options (can override the top-level defaults).diff --git a/engine/tests/es-compat-yaml/yaml/search/730_highlight_field_patterns.yml b/engine/tests/es-compat-yaml/yaml/search/730_highlight_field_patterns.ymlnew file mode 100644index 000000000..b3539a513--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/search/730_highlight_field_patterns.yml@@ -0,0 +1,39 @@+setup:+ - do:+ indices.create:+ index: highlight_patterns+ body:+ mappings:+ properties:+ message:+ type: text+ title:+ type: text+ - do:+ bulk:+ refresh: true+ body:+ - '{"index": {"_index": "highlight_patterns", "_id": "1"}}'+ - '{"message": "upstream timeout contacting backend", "title": "timeout report"}'++---+"highlight field patterns are expanded against the mapping (#1281)":+ - do:+ search:+ index: highlight_patterns+ body:+ query: { match: { message: timeout } }+ highlight: { fields: { "*": {} } }++ - match: { hits.hits.0.highlight.message.0: "upstream <em>timeout</em> contacting backend" }+ - is_false: hits.hits.0.highlight.title++ - do:+ search:+ index: highlight_patterns+ body:+ query: { match: { message: timeout } }+ highlight: { require_field_match: false, fields: { "t*": {} } }++ - match: { hits.hits.0.highlight.title.0: "<em>timeout</em> report" }+ - is_false: hits.hits.0.highlight.message