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(mapping): honour `index: false` instead of silently ignoring it
xerj-org074276238e3b
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 91c93f51d..315358f9d 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -13575,6 +13575,23 @@ fn es_properties_to_fields(properties: &Value) -> Vec<FieldConfig> {.and_then(Value::as_bool).unwrap_or(doc_values_default);+ // `index` — the sibling of `doc_values` above, and the last open+ // instance of the accepted-and-ignored class in #204. `"index": false`+ // was parsed nowhere, echoed back verbatim by `GET _mapping`, and had+ // no effect at all: the field kept its inverted index and every query+ // against it kept matching.+ //+ // Carrying the declared intent here is what makes the two halves of+ // the fix possible — `fts_excluded_fields` (xerj-engine) drops the+ // field from the inverted index at flush/merge, and+ // `unsearchable_query_field` (xerj-engine) rejects queries that ES+ // rejects. Default `true` mirrors ES: every field is indexed unless+ // the mapping says otherwise.+ fc.options.indexed = field_def+ .get("index")+ .and_then(Value::as_bool)+ .unwrap_or(true);+// Handle copy_to: store the target field in a special null_value marker.if let Some(copy_target) = field_def.get("copy_to").and_then(Value::as_str) {fc.options.null_value = Some(Value::String(format!("__copy_to__:{}", copy_target)));diff --git a/engine/crates/xerj-api/tests/index_false_is_honoured.rs b/engine/crates/xerj-api/tests/index_false_is_honoured.rsnew file mode 100644index 000000000..d6ffae8e1--- /dev/null+++ b/engine/crates/xerj-api/tests/index_false_is_honoured.rs@@ -0,0 +1,320 @@+//! `"index": false` on a mapping, from the outside — the last open instance of+//! the accepted-and-ignored class tracked in #204.+//!+//! Before this test's fix the option was parsed nowhere. `PUT /{index}` took+//! it, `GET /{index}/_mapping` echoed it back verbatim, and the engine went on+//! building a full inverted index for the field and answering every query+//! against it. A user who wrote `"index": false` to make a field+//! store-but-don't-search got neither half of that promise: the postings were+//! still built, and a `match` on the field still returned the document.+//!+//! The convention #204 establishes is *accepted means honoured*, so the option+//! is now honoured on both sides:+//!+//! * a query naming a field that has neither postings nor doc values is+//! rejected with ES's own sentence instead of being answered from+//! `_source` (`index::unsearchable_query_field`), and+//! * the field is dropped from the full-text index at flush and merge+//! wherever the stored-doc scan is an equivalent fallback+//! (`memtable::fts_excluded_fields`).+//!+//! Both halves are deliberately narrower than "reject everything / drop+//! everything", because ES 8.1 added *doc values search*: `"index": false` on+//! a keyword/numeric/date/boolean/ip field keeps its doc values and stays+//! queryable, just slower — the whole of `search/390_doc_values_search.yml`+//! depends on it. Only a field with no postings AND no doc values (a `text`+//! field, or anything with an explicit `"doc_values": false`) is unsearchable,+//! and that is exactly what ES rejects with+//! `Cannot search on field [f] since it is not indexed nor has doc values.`+//!+//! Elasticsearch is referenced for semantics only. It is AGPL-3.0/SSPL-1.0/+//! Elastic-2.0 licensed and no code from it 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 send(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {+ let response = app.clone().oneshot(req).await.expect("response");+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body");+ let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ (status, value)+}++async fn json_req(+ app: &axum::Router,+ method: &str,+ path: &str,+ body: Value,+) -> (StatusCode, Value) {+ send(+ app,+ Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request"),+ )+ .await+}++async fn get(app: &axum::Router, path: &str) -> (StatusCode, Value) {+ send(+ app,+ Request::get(path).body(Body::empty()).expect("request"),+ )+ .await+}++async fn search(app: &axum::Router, query: Value) -> (StatusCode, Value) {+ json_req(app, "POST", "/t/_search", json!({ "query": query })).await+}++/// `note` — text, `index: false` → no postings, no doc values: UNSEARCHABLE.+/// `secret` — keyword, `index: false` + `doc_values: false`: UNSEARCHABLE.+/// `code` — keyword, `index: false` → keeps doc values: still queryable.+/// `body` — a plain indexed text field, the control.+async fn app_with_mapping() -> (axum::Router, tempfile::TempDir) {+ let (app, dir) = app().await;+ let (status, body) = json_req(+ &app,+ "PUT",+ "/t",+ json!({+ "mappings": {+ "properties": {+ "note": { "type": "text", "index": false },+ "secret": { "type": "keyword", "index": false, "doc_values": false },+ "code": { "type": "keyword", "index": false },+ "body": { "type": "text" }+ }+ }+ }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "create index failed: {body}");++ let (status, body) = json_req(+ &app,+ "PUT",+ "/t/_doc/1?refresh=true",+ json!({+ "note": "confidential memo about pelicans",+ "secret": "hunter2",+ "code": "AB-1234",+ "body": "confidential memo about pelicans"+ }),+ )+ .await;+ assert!(+ status.is_success(),+ "index document failed: {status} {body}"+ );+ // Force the memtable out to a segment so the FTS-exclusion half is+ // exercised on the flushed/merged path, not only in the memtable.+ let (status, _) = json_req(&app, "POST", "/t/_refresh", json!({})).await;+ assert!(status.is_success(), "refresh failed: {status}");+ (app, dir)+}++/// Accepted, echoed, and now honoured: the option survives the mapping+/// round-trip and the value is still stored and returned.+#[tokio::test]+async fn mapping_still_echoes_index_false_and_source_is_intact() {+ let (app, _dir) = app_with_mapping().await;++ let (status, mapping) = get(&app, "/t/_mapping").await;+ assert_eq!(status, StatusCode::OK, "GET _mapping failed: {mapping}");+ assert_eq!(+ mapping.pointer("/t/mappings/properties/note/index"),+ Some(&json!(false)),+ "GET _mapping must keep echoing `index: false`: {mapping}"+ );+ assert_eq!(+ mapping.pointer("/t/mappings/properties/note/type"),+ Some(&json!("text")),+ "{mapping}"+ );++ let (status, doc) = get(&app, "/t/_doc/1").await;+ assert_eq!(status, StatusCode::OK, "GET _doc failed: {doc}");+ assert_eq!(+ doc.pointer("/_source/note").and_then(Value::as_str),+ Some("confidential memo about pelicans"),+ "a non-indexed field is still stored and returned: {doc}"+ );+}++/// THE REGRESSION. Before the fix this returned 200 with one hit, because the+/// field kept its postings and the stored-doc scan matched it from `_source`.+#[tokio::test]+async fn querying_a_field_with_no_postings_and_no_doc_values_is_rejected() {+ let (app, _dir) = app_with_mapping().await;++ for query in [+ json!({ "match": { "note": "pelicans" } }),+ json!({ "term": { "note": "pelicans" } }),+ json!({ "match_phrase": { "note": "confidential memo" } }),+ json!({ "prefix": { "note": { "value": "pel" } } }),+ json!({ "wildcard": { "note": { "value": "pel*" } } }),+ // Nested inside a bool filter — the walk must recurse, not just peek+ // at the top-level clause.+ json!({ "bool": { "filter": [ { "term": { "note": "pelicans" } } ] } }),+ // …and inside must_not, where a silent non-match would invert the+ // result set rather than merely shrink it.+ json!({ "bool": { "must_not": [ { "match": { "note": "pelicans" } } ] } }),+ ] {+ let (status, body) = search(&app, query.clone()).await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "query {query} must be rejected, got {status}: {body}"+ );+ assert_eq!(+ body.pointer("/error/type").and_then(Value::as_str),+ Some("search_phase_execution_exception"),+ "{body}"+ );+ assert_eq!(+ body.pointer("/error/root_cause/0/type")+ .and_then(Value::as_str),+ Some("query_shard_exception"),+ "{body}"+ );+ let reason = body+ .pointer("/error/root_cause/0/reason")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ reason.contains(+ "Cannot search on field [note] since it is not indexed nor has doc values."+ ),+ "reason must carry ES's sentence, got {reason:?}: {body}"+ );+ }++ // An explicit `doc_values: false` reaches the same verdict on a keyword.+ let (status, body) = search(&app, json!({ "term": { "secret": "hunter2" } })).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");+ let reason = body+ .pointer("/error/root_cause/0/reason")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ reason.contains("Cannot search on field [secret]"),+ "got {reason:?}: {body}"+ );+}++/// `index: false` is not "unqueryable" on its own. ES 8.1's doc-values search+/// still answers term/terms/range on a keyword that kept its doc values, and so+/// must XERJ — otherwise honouring the option would break+/// `search/390_doc_values_search.yml`.+#[tokio::test]+async fn index_false_with_doc_values_stays_queryable() {+ let (app, _dir) = app_with_mapping().await;++ for query in [+ json!({ "term": { "code": "AB-1234" } }),+ json!({ "terms": { "code": ["AB-1234", "ZZ-0000"] } }),+ ] {+ let (status, body) = search(&app, query.clone()).await;+ assert_eq!(status, StatusCode::OK, "query {query} → {status}: {body}");+ assert_eq!(+ body.pointer("/hits/total/value").and_then(Value::as_u64),+ Some(1),+ "doc-values search must still find the doc for {query}: {body}"+ );+ }+}++/// No collateral damage: an ordinary indexed field is unaffected, and `exists`+/// on an unsearchable field is 0 hits rather than an error (ES leaves such a+/// field out of `_field_names`; it does not fail the query).+#[tokio::test]+async fn indexed_fields_and_exists_are_unaffected() {+ let (app, _dir) = app_with_mapping().await;++ let (status, body) = search(&app, json!({ "match": { "body": "pelicans" } })).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ body.pointer("/hits/total/value").and_then(Value::as_u64),+ Some(1),+ "the indexed control field must still match: {body}"+ );++ let (status, body) = search(&app, json!({ "exists": { "field": "note" } })).await;+ assert_eq!(+ status,+ StatusCode::OK,+ "`exists` on an unsearchable field is not an error in ES: {body}"+ );+ assert_eq!(+ body.pointer("/hits/total/value").and_then(Value::as_u64),+ Some(0),+ "{body}"+ );+}++/// The check runs AFTER alias resolution, so an alias cannot be used to reach+/// a field the mapping made unsearchable.+#[tokio::test]+async fn an_alias_to_an_unsearchable_field_is_rejected_too() {+ let (app, _dir) = app().await;+ let (status, body) = json_req(+ &app,+ "PUT",+ "/t",+ json!({+ "mappings": {+ "properties": {+ "note": { "type": "text", "index": false },+ "note_alias": { "type": "alias", "path": "note" },+ "body": { "type": "text" }+ }+ }+ }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");++ let (status, body) = json_req(+ &app,+ "PUT",+ "/t/_doc/1?refresh=true",+ json!({ "note": "zzquagga", "body": "ordinary text" }),+ )+ .await;+ assert!(status.is_success(), "{status} {body}");++ let (status, body) = search(&app, json!({ "match": { "note_alias": "zzquagga" } })).await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "an alias must inherit its target's searchability: {body}"+ );+ let reason = body+ .pointer("/error/root_cause/0/reason")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ reason.contains("Cannot search on field [note]"),+ "the error names the resolved target, as ES does: {reason:?}"+ );+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 66a2a0ccf..8771f1777 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -6908,7 +6908,7 @@ impl Index {let analyzer = mem.default_analyzer().expect("standard analyzer always present");- let excluded_fts_fields = crate::memtable::semantic_derived_vector_fields(schema);+ let excluded_fts_fields = crate::memtable::fts_excluded_fields(schema);let p_t = std::time::Instant::now();let analyzed: Vec<Vec<(String, Vec<xerj_fts::analyzer::Token>)>> = crate::ingest_pool().install(|| {@@ -7379,9 +7379,7 @@ impl Index {let registry = Arc::clone(&self.registry);let data_dir = self.data_dir.clone();let field_configs = self.flush_signal.field_configs(&self.schema);- let excluded_fts_fields = self- .flush_signal- .semantic_derived_vector_fields(&self.schema);+ let excluded_fts_fields = self.flush_signal.fts_excluded_fields(&self.schema);let dv_skip = self.flush_signal.doc_values_skip_set(&self.schema);let dataset_version = Arc::clone(&self.dataset_version);let query_cache = Arc::clone(&self.query_cache);@@ -7632,7 +7630,7 @@ impl Index {let schema = self.schema.read().await;(build_fts_field_configs(&schema.schema),- crate::memtable::semantic_derived_vector_fields(&schema.schema),+ crate::memtable::fts_excluded_fields(&schema.schema),doc_values_skip_set(&schema.schema),)};@@ -7768,7 +7766,7 @@ impl Index {let (excluded_fts_fields, dv_skip) = {let schema = self.schema.read().await;(- crate::memtable::semantic_derived_vector_fields(&schema.schema),+ crate::memtable::fts_excluded_fields(&schema.schema),doc_values_skip_set(&schema.schema),)};@@ -8008,7 +8006,7 @@ impl Index {let schema = self.schema.read().await;(build_fts_field_configs(&schema.schema),- crate::memtable::semantic_derived_vector_fields(&schema.schema),+ crate::memtable::fts_excluded_fields(&schema.schema),)};// Kept for the legacy "if !text_fields.is_empty()" branch — empty@@ -12899,9 +12897,25 @@ impl Index {let from = request.from;// Resolve field aliases in the query: rewrite any alias field names to their targets.+ //+ // The unsearchable-field check rides on the same schema guard, and runs+ // AFTER alias resolution so an alias inherits its target's mapping —+ // which is what ES validates. See `unsearchable_query_field`: a field+ // declared `"index": false` with no doc values has neither postings nor+ // a column to scan, and ES fails the query rather than answering it+ // from `_source` (#204 — accepted means honoured).let resolved_query = {let schema = self.schema.read().await;- rewrite_query_aliases(&request.query, &schema.schema)+ let resolved = rewrite_query_aliases(&request.query, &schema.schema);+ if let Some(field) = unsearchable_query_field(&resolved, &schema.schema) {+ return Err(EngineError::Common(xerj_common::XerjError::invalid_query(+ format!(+ "failed to create query: Cannot search on field [{field}] \+ since it is not indexed nor has doc values."+ ),+ )));+ }+ resolved};let query = &resolved_query;@@ -13263,6 +13277,27 @@ impl Index {let mut num: std::collections::HashSet<String> = std::collections::HashSet::new();let mut bf: std::collections::HashSet<String> = std::collections::HashSet::new();for f in &schema_guard.schema.fields {+ // These sets are the field-less expansion: what a bare+ // `query_string` / `simple_query_string` / `multi_match` on+ // `*` projects a clause onto. ES expands `*` over SEARCHABLE+ // fields only (`MappedFieldType.isSearchable()` = has terms OR+ // has doc values), so a field declared `"index": false` with no+ // doc values must not appear here — otherwise the projected+ // clause falls through the per-segment `fts_has_field` gate+ // onto the stored-doc scan and matches the field's `_source`+ // text, which is the accepted-and-ignored bug wearing a+ // different hat (#204). A named query on the same field is+ // rejected outright by `unsearchable_query_field`; this is the+ // implicit-expansion half of the same rule.+ //+ // `index: false` WITH doc values stays in: ES calls it+ // searchable and answers it from the column (8.1 doc-values+ // search). We answer it exactly too — see+ // `memtable::fts_excluded_fields` for why such a field keeps+ // its postings rather than falling back to the scan.+ if !f.options.indexed && !f.options.doc_values {+ continue;+ }if matches!(f.field_type, FieldType::Text) {tf.push(f.name.clone());} else {@@ -16767,7 +16802,7 @@ impl Index {let schema = self.schema.read().await;(build_fts_field_configs(&schema.schema),- crate::memtable::semantic_derived_vector_fields(&schema.schema),+ crate::memtable::fts_excluded_fields(&schema.schema),doc_values_skip_set(&schema.schema),)};@@ -17972,7 +18007,7 @@ fn read_doc_values_sidecar(fn build_fts_field_configs(schema: &Schema) -> HashMap<String, xerj_fts::index::FieldIndexConfig> {use xerj_fts::index::FieldIndexConfig;let mut out = HashMap::new();- let excluded = crate::memtable::semantic_derived_vector_fields(schema);+ let excluded = crate::memtable::fts_excluded_fields(schema);for f in &schema.fields {if excluded.contains(&f.name) {continue;@@ -23517,7 +23552,7 @@ impl SyncFlushCoord {})}- fn semantic_derived_vector_fields(+ fn fts_excluded_fields(&self,schema: &Arc<RwLock<ManagedSchema>>,) -> std::collections::HashSet<String> {@@ -23526,7 +23561,7 @@ impl SyncFlushCoord {};rt.block_on(async {let guard = schema.read().await;- crate::memtable::semantic_derived_vector_fields(&guard.schema)+ crate::memtable::fts_excluded_fields(&guard.schema)})}}@@ -26848,6 +26883,144 @@ fn lookup_vector_quantization(schema: &Schema, field: &str) -> Option<String> {find(&schema.fields, &parts).and_then(|fc| fc.options.quantization.clone())}+/// Resolve a (possibly dotted) field path to its declared [`FieldConfig`].+///+/// Same walk as `lookup_vector_quantization`: a dotted path descends through+/// `FieldConfig::fields` (object sub-paths and multi-fields). Returns `None`+/// for anything the schema does not declare — dynamic fields have no declared+/// mapping options to honour.+fn declared_field<'a>(schema: &'a Schema, field: &str) -> Option<&'a FieldConfig> {+ fn find<'a>(fields: &'a [FieldConfig], path: &[&str]) -> Option<&'a FieldConfig> {+ let head = *path.first()?;+ let tail = &path[1..];+ for fc in fields {+ if fc.name == head {+ if tail.is_empty() {+ return Some(fc);+ }+ return find(&fc.fields, tail);+ }+ }+ None+ }+ find(&schema.fields, &field.split('.').collect::<Vec<_>>())+}++/// The first field in `q` that the mapping has made completely unsearchable.+///+/// A field is unsearchable when its mapping declares BOTH `"index": false`+/// (no postings) and no doc values (nothing to scan instead) — for example+/// `{"type": "text", "index": false}`, since `text` has no doc values by+/// default. ES rejects every query naming such a field with+/// `IllegalArgumentException: Cannot search on field [f] since it is not+/// indexed nor has doc values.`, which its shard query builder wraps as a+/// `query_shard_exception` inside a 400 `search_phase_execution_exception`.+/// XERJ's `XerjError::InvalidQuery` + the `failed to create query:` prefix+/// reproduce exactly that envelope (see `xerj-api/src/error.rs`).+///+/// `index: false` WITH doc values is *not* unsearchable: ES 8.1 added "doc+/// values search" and answers term/terms/range/prefix/wildcard/regexp/fuzzy+/// from the doc-values column instead (the whole of+/// `search/390_doc_values_search.yml`). Those queries keep working here too,+/// unchanged: such a field keeps its whole-value postings, because they are+/// what answers it *exactly* — see `memtable::fts_excluded_fields`.+///+/// Deliberately NOT covered: the multi-field query types (`multi_match`,+/// `query_string`, `simple_query_string`, `more_like_this`). ES throws when+/// any *named* field is unsearchable, but XERJ expands wildcard field specs+/// against the schema, so rejecting here would turn `fields: ["*"]` into a+/// hard error for the whole index.+///+/// The FTS route for those queries no longer projects a clause onto an+/// unsearchable field (`text_fields`/`exact_fields` in `search_inner` apply+/// ES's `isSearchable()` rule), but the stored-doc scan's field-less+/// `query_string` arm is schema-free: it walks every non-`_` key of+/// `_source`, so a token living only in an unsearchable field still matches+/// there. Measured, not assumed. That arm's divergence from the FTS+/// projection predates this change and is called out in its own comment in+/// `doc_matches_query`; making it schema-aware means threading a schema+/// through ~79 call sites and is left as its own change.+fn unsearchable_query_field(q: &QueryNode, schema: &Schema) -> Option<String> {+ let check = |field: &String| -> Option<String> {+ let fc = declared_field(schema, field)?;+ (!fc.options.indexed && !fc.options.doc_values).then(|| field.clone())+ };+ match q {+ // ── Leaves that name exactly one field ────────────────────────────+ 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, .. }+ | QueryNode::Intervals { field, .. }+ | QueryNode::SpanTerm { field, .. }+ | QueryNode::GeoDistance { field, .. }+ | QueryNode::GeoBoundingBox { field, .. }+ | QueryNode::GeoPolygon { field, .. }+ | QueryNode::GeoShape { field, .. } => check(field),++ // `exists` is NOT an error in ES: an unsearchable field is simply+ // absent from `_field_names`, so the clause matches nothing. The+ // API layer already rewrites it to `match_none`+ // (`es_compat::rewrite_unqueryable_exists`).+ QueryNode::Exists { .. } => None,++ // ── Composites: recurse ───────────────────────────────────────────+ QueryNode::Bool {+ must,+ should,+ must_not,+ filter,+ ..+ } => must+ .iter()+ .chain(should)+ .chain(must_not)+ .chain(filter)+ .find_map(|c| unsearchable_query_field(c, schema)),+ QueryNode::Constant { query, .. }+ | QueryNode::Boosted { query, .. }+ | QueryNode::Named { query, .. }+ | QueryNode::Nested { query, .. }+ | QueryNode::FunctionScore { query, .. } => unsearchable_query_field(query, schema),+ QueryNode::Pinned { organic, .. } => unsearchable_query_field(organic, schema),+ QueryNode::Boosting {+ positive, negative, ..+ } => unsearchable_query_field(positive, schema)+ .or_else(|| unsearchable_query_field(negative, schema)),+ QueryNode::DisMax { queries, .. } => queries+ .iter()+ .find_map(|c| unsearchable_query_field(c, schema)),+ QueryNode::Hybrid { queries, .. } => queries+ .iter()+ .find_map(|wq| unsearchable_query_field(&wq.query, schema)),+ QueryNode::Knn { filter, .. } | QueryNode::SemanticSearch { filter, .. } => filter+ .as_ref()+ .and_then(|f| unsearchable_query_field(f, schema)),+ QueryNode::SpanNear { clauses, .. } | QueryNode::SpanOr { clauses } => clauses+ .iter()+ .find_map(|c| unsearchable_query_field(c, schema)),+ QueryNode::SpanNot { include, exclude } => unsearchable_query_field(include, schema)+ .or_else(|| unsearchable_query_field(exclude, schema)),+ QueryNode::SpanFirst { match_query, .. } => unsearchable_query_field(match_query, schema),+ QueryNode::SpanContaining { little, big } | QueryNode::SpanWithin { little, big } => {+ unsearchable_query_field(little, schema)+ .or_else(|| unsearchable_query_field(big, schema))+ }++ // Everything else names no single mapped field to validate:+ // MatchAll/MatchNone/Ids/Script, the multi-field types documented+ // above, `percolate` (the field holds stored queries, not data), and+ // `more_like_this`.+ _ => None,+ }+}+/// Rewrite a query by resolving any field aliases to their canonical field names.////// Traverses the query tree, replacing alias field names with their target paths.@@ -38158,7 +38331,7 @@ mod flush_memory_integration_tests {let schema = idx.schema.read().await;(build_fts_field_configs(&schema.schema),- crate::memtable::semantic_derived_vector_fields(&schema.schema),+ crate::memtable::fts_excluded_fields(&schema.schema),doc_values_skip_set(&schema.schema),)};diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rsindex 0005b41fa..90416fd5a 100644--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@ -3576,7 +3576,7 @@ pub fn analyze_doc(schema: &Schema,analyzer: &AnalyzerPipeline,) -> Vec<(String, Vec<Token>)> {- let excluded = semantic_derived_vector_fields(schema);+ let excluded = fts_excluded_fields(schema);analyze_doc_excluding(source, schema, analyzer, &excluded)}@@ -3590,6 +3590,14 @@ pub fn analyze_doc_excluding(// Index fields that are defined as Text in the schema.for field_cfg in &schema.fields {+ // `excluded` is authoritative for schema fields too, not only for the+ // dynamic-path sweep below. Before `index: false` was honoured the only+ // members were semantic-derived vector fields, which are never+ // `FieldType::Text`, so this loop could skip the check; a declared+ // `"index": false` Text field is exactly the case that needs it.+ if excluded.contains(&field_cfg.name) {+ continue;+ }if matches!(field_cfg.field_type, FieldType::Text) {if let Some(val) = source.get(&field_cfg.name) {let text = extract_text_value(val);@@ -3640,6 +3648,61 @@ pub fn semantic_derived_vector_fields(schema: &Schema) -> std::collections::Hashexcluded}+/// Every field that must be kept OUT of the full-text inverted index.+///+/// Two disjoint reasons, unioned into one set so flush, merge, the memtable+/// analyser and `build_fts_field_configs` cannot disagree:+///+/// * semantic-derived vector fields (see above) — engine-internal payloads+/// that were never user text;+/// * fields whose mapping declares `"index": false` — #204's last open+/// accepted-and-ignored instance. The option was echoed by `GET _mapping`+/// and then ignored, so the field kept a full inverted index and stayed+/// searchable.+///+/// Derived from the SCHEMA rather than from the documents, exactly like+/// `doc_values_skip_set` — a merge must not resurrect postings that flush+/// correctly skipped. Dynamic (unmapped) fields are absent from the schema+/// and are unaffected: there is no declared `index: false` to honour.+///+/// ## Why `index: false` alone is not enough to drop the postings+///+/// Dropping a field's postings does not make it unmatchable here: the+/// per-segment `fts_has_field` gate routes the query onto the stored-doc+/// scan instead. That fallback is only usable where it is *equivalent* —+/// #204's second rule, "degrade loudly or not at all", applies to us as much+/// as to anyone.+///+/// * A **Text** field's scan comparison is analysed, which is exactly what+/// the postings did. Equivalent → the postings go.+/// * An **exact-typed** field (keyword / ip / date / numeric / boolean) is+/// FTS-indexed with the `keyword` analyzer: one whole-value token. The+/// scan's `match` arm splits on non-alphanumerics, so `192.168.0.1` would+/// start matching `192.168.0.2`. Measured, not theorised — it is the one+/// case `search/390_doc_values_search.yml` fails on. Weaker → the postings+/// stay, and they are what answers ES 8.1's "doc values search" exactly.+/// Nothing observable changes for those fields; the footprint saving is+/// knowingly forgone rather than bought with wrong answers.+/// * A field with **no doc values either** is unsearchable in ES's sense+/// (`MappedFieldType.isSearchable()` = has terms OR has doc values), and+/// `unsearchable_query_field` in `index.rs` rejects every query naming it+/// before execution — so no fallback of any strength ever runs, and the+/// postings are pure waste whatever the type.+pub fn fts_excluded_fields(schema: &Schema) -> std::collections::HashSet<String> {+ let mut excluded = semantic_derived_vector_fields(schema);+ for field in &schema.fields {+ if field.options.indexed {+ continue;+ }+ let fallback_is_equivalent =+ matches!(field.field_type, FieldType::Text) || !field.options.doc_values;+ if fallback_is_equivalent {+ excluded.insert(field.name.clone());+ }+ }+ excluded+}+#[cfg(test)]mod semantic_derived_vector_exclusion_tests {use super::*;@@ -3715,6 +3778,95 @@ mod semantic_derived_vector_exclusion_tests {}}+#[cfg(test)]+mod index_false_exclusion_tests {+ //! `"index": false` must remove the field from the full-text index —+ //! the storage half of #204's last accepted-and-ignored instance. Before+ //! the fix `FieldOptions::indexed` was never read here, so a field the+ //! mapping declared non-indexed got a full set of postings anyway.+ use super::*;+ use serde_json::json;+ use xerj_common::types::{FieldConfig, FieldType};++ fn schema_with_a_non_indexed_field() -> Schema {+ let mut schema = Schema::empty();+ let mut note = FieldConfig::new("note", FieldType::Text);+ note.options.indexed = false;+ note.options.doc_values = false;+ schema.add_field(note).unwrap();+ let mut code = FieldConfig::new("code", FieldType::Keyword);+ code.options.indexed = false; // keeps doc values — still queryable+ schema.add_field(code).unwrap();+ schema+ .add_field(FieldConfig::new("body", FieldType::Text))+ .unwrap();+ schema+ }++ #[test]+ fn non_indexed_fields_join_the_fts_exclusion_set() {+ let schema = schema_with_a_non_indexed_field();+ let excluded = fts_excluded_fields(&schema);+ assert!(+ excluded.contains("note"),+ "a non-indexed Text field: the stored-doc scan analyses it the \+ same way the postings did, so dropping them is equivalent: \+ {excluded:?}"+ );+ assert!(+ !excluded.contains("code"),+ "a non-indexed KEYWORD that kept its doc values is still \+ searchable in ES's sense, and the scan fallback is weaker than \+ its whole-value postings (it would split `192.168.0.1` into \+ tokens) — the postings stay: {excluded:?}"+ );+ assert!(!excluded.contains("body"), "{excluded:?}");++ // …but with no doc values either, nothing can answer it, the query is+ // rejected outright, and the postings are pure waste whatever the type.+ let mut schema = Schema::empty();+ let mut opaque = FieldConfig::new("opaque", FieldType::Keyword);+ opaque.options.indexed = false;+ opaque.options.doc_values = false;+ schema.add_field(opaque).unwrap();+ assert!(fts_excluded_fields(&schema).contains("opaque"));+ }++ #[test]+ fn a_non_indexed_schema_text_field_is_never_analysed() {+ // The schema-Text loop in `analyze_doc_excluding` used to ignore the+ // exclusion set entirely (its only members were semantic-derived+ // vector fields, which are never Text). A declared `index: false`+ // Text field is exactly the case that made the omission visible.+ let schema = schema_with_a_non_indexed_field();+ let source = json!({ "note": "zzquagga", "code": "AB-1234", "body": "ordinary text" });+ let analyzer = xerj_fts::analyzer::AnalyzerPipeline::new(+ vec![],+ std::sync::Arc::new(xerj_fts::analyzer::StandardTokenizer),+ vec![std::sync::Arc::new(xerj_fts::analyzer::LowercaseFilter)+ as std::sync::Arc<dyn xerj_fts::analyzer::TokenFilter>],+ );+ let analysed: std::collections::HashMap<String, Vec<Token>> =+ analyze_doc(&source, &schema, &analyzer)+ .into_iter()+ .collect();+ let names: Vec<&str> = analysed.keys().map(String::as_str).collect();+ assert!(+ !analysed.contains_key("note"),+ "a non-indexed Text field must contribute no tokens: {names:?}"+ );+ assert!(+ analysed.contains_key("code"),+ "`code` kept its doc values, so it kept its whole-value postings \+ too — see `fts_excluded_fields`: {names:?}"+ );+ assert!(+ analysed.contains_key("body"),+ "the indexed control field must still be analysed: {names:?}"+ );+ }+}+/// Extract a string value from a JSON value for text indexing.fn extract_text_value(val: &Value) -> String {match val {