Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

[search] deprecate parent-child migration legacy code (#3827)

gbirman47a0bd05b158
diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
index fc302a474e..fbe4522076 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
@@ -30,6 +30,3 @@ config:
cloud-storage-service:anthropic_api_key: anthropic-api-key-dev
cloud-storage-service:openai_api_key: openai-key
cloud-storage-service:apple_bundle_id: apple-bundle-id-prod
- cloud-storage-service:documents_index_uses_join: "true"
- cloud-storage-service:chats_index_uses_join: "true"
- cloud-storage-service:call_records_index_uses_join: "true"
diff --git a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
index c7f0f5b52d..73e2f6c0f2 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
@@ -30,6 +30,3 @@ config:
cloud-storage-service:anthropic_api_key: anthropic-api-key
cloud-storage-service:openai_api_key: openai-key
cloud-storage-service:apple_bundle_id: apple-bundle-id-prod
- cloud-storage-service:documents_index_uses_join: "true"
- cloud-storage-service:call_records_index_uses_join: "true"
- cloud-storage-service:chats_index_uses_join: "true"
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index 4b5a2f5a44..9779cb7ce7 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -471,28 +471,6 @@ const cloudStorageService = new CloudStorageService(
name: 'OPENSEARCH_PASSWORD',
value: OPENSEARCH_PASSWORD,
},
- {
- // Flips the documents alias dispatch in opensearch_client between
- // the flat-chunk shape (`documents_v1`) and the parent/child join
- // shape (`documents_v2`). Set via Pulumi config and flipped at
- // cutover; defaults to `false` so the existing flat-shape paths
- // stay active until the alias is swapped.
- name: 'DOCUMENTS_INDEX_USES_JOIN',
- value: config.get('documents_index_uses_join') ?? 'false',
- },
- {
- // Same as DOCUMENTS_INDEX_USES_JOIN, but for the chats alias
- // (`chats_v1` flat -> `chats_v2` parent/child).
- name: 'CHATS_INDEX_USES_JOIN',
- value: config.get('chats_index_uses_join') ?? 'false',
- },
- {
- // Same as DOCUMENTS_INDEX_USES_JOIN, but for the call_records
- // alias (`call_records_v1` flat -> `call_records_v2`
- // parent/child).
- name: 'CALL_RECORDS_INDEX_USES_JOIN',
- value: config.get('call_records_index_uses_join') ?? 'false',
- },
{
name: 'DATABASE_URL',
value: pulumi.interpolate`${DATABASE_URL}`,
diff --git a/infra/stacks/search-processing-service/Pulumi.dev.yaml b/infra/stacks/search-processing-service/Pulumi.dev.yaml
index 4871a60e93..6147290457 100644
--- a/infra/stacks/search-processing-service/Pulumi.dev.yaml
+++ b/infra/stacks/search-processing-service/Pulumi.dev.yaml
@@ -4,6 +4,3 @@ config:
search-processing-service:macro_db_readonly_secret_key: macro-db-readonly-dev
search-processing-service:opensearch_password_key: macro-opensearch-password-dev
search-processing-service:internal_auth_key: document-storage-service-auth-key-dev
- search-processing-service:documents_index_uses_join: "true"
- search-processing-service:chats_index_uses_join: "true"
- search-processing-service:call_records_index_uses_join: "true"
diff --git a/infra/stacks/search-processing-service/Pulumi.prod.yaml b/infra/stacks/search-processing-service/Pulumi.prod.yaml
index 5f05ce24ed..0bf13c55f1 100644
--- a/infra/stacks/search-processing-service/Pulumi.prod.yaml
+++ b/infra/stacks/search-processing-service/Pulumi.prod.yaml
@@ -4,6 +4,3 @@ config:
search-processing-service:macro_db_readonly_secret_key: macro-db-readonly-prod
search-processing-service:opensearch_password_key: macro-opensearch-password-prod
search-processing-service:internal_auth_key: document-storage-service-auth-key-prod
- search-processing-service:documents_index_uses_join: "true"
- search-processing-service:call_records_index_uses_join: "true"
- search-processing-service:chats_index_uses_join: "true"
diff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.ts
index 3db208a7c4..73cbb7980e 100644
--- a/infra/stacks/search-processing-service/index.ts
+++ b/infra/stacks/search-processing-service/index.ts
@@ -141,28 +141,6 @@ const searchProcessingService = new SearchProcessingService(
name: 'OPENSEARCH_PASSWORD',
value: OPENSEARCH_PASSWORD,
},
- {
- // Flips the documents alias dispatch in opensearch_client between
- // the flat-chunk shape (`documents_v1`) and the parent/child join
- // shape (`documents_v2`). Set via Pulumi config and flipped at
- // cutover; defaults to `false` so the existing flat-shape paths
- // stay active until the alias is swapped.
- name: 'DOCUMENTS_INDEX_USES_JOIN',
- value: config.get('documents_index_uses_join') ?? 'false',
- },
- {
- // Same as DOCUMENTS_INDEX_USES_JOIN, but for the chats alias
- // (`chats_v1` flat -> `chats_v2` parent/child).
- name: 'CHATS_INDEX_USES_JOIN',
- value: config.get('chats_index_uses_join') ?? 'false',
- },
- {
- // Same as DOCUMENTS_INDEX_USES_JOIN, but for the call_records
- // alias (`call_records_v1` flat -> `call_records_v2`
- // parent/child).
- name: 'CALL_RECORDS_INDEX_USES_JOIN',
- value: config.get('call_records_index_uses_join') ?? 'false',
- },
{
name: 'DOCUMENT_STORAGE_BUCKET',
value: pulumi.interpolate`${documentStorageBucketId}`,
diff --git a/rust/cloud-storage/opensearch_client/src/call_records_shape.rs b/rust/cloud-storage/opensearch_client/src/call_records_shape.rs
deleted file mode 100644
index 03faf46e21..0000000000
--- a/rust/cloud-storage/opensearch_client/src/call_records_shape.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-//! Dispatch helpers for the call_records index migration from a flat
-//! one-doc-per-segment shape to a parent/child join shape.
-//!
-//! Mirrors [`crate::documents_shape`] and [`crate::chats_shape`].
-
-use std::sync::OnceLock;
-
-/// Physical name of the join-shape call_records index. Used as the
-/// `index_override` value for backfills that should write in the join
-/// shape and as the trigger for `destination_uses_join_shape`.
-pub const CALL_RECORDS_V2: &str = "call_records_v2";
-
-/// Default alias name reads target. Production code always uses this.
-const DEFAULT_CALL_RECORDS_ALIAS: &str = "call_records";
-
-/// Whether writes targeting this destination should use the parent/child
-/// join shape.
-pub fn destination_uses_join_shape(destination: &str) -> bool {
- if destination == CALL_RECORDS_V2 {
- return true;
- }
- if destination == DEFAULT_CALL_RECORDS_ALIAS {
- return alias_uses_join_shape();
- }
- false
-}
-
-/// Whether the `call_records` alias currently resolves to a join-shape
-/// index.
-///
-/// Controlled by the `CALL_RECORDS_INDEX_USES_JOIN` env var, cached once
-/// per process. Operators set it `true` at the alias swap; before then
-/// it defaults to `false` so the existing flat-shape paths stay active.
-pub fn alias_uses_join_shape() -> bool {
- static ALIAS_USES_JOIN: OnceLock<bool> = OnceLock::new();
- *ALIAS_USES_JOIN.get_or_init(|| {
- std::env::var("CALL_RECORDS_INDEX_USES_JOIN")
- .map(|v| v == "true")
- .unwrap_or(false)
- })
-}
-
-/// Alias name that search reads target for call records. Returns
-/// `call_records` by default; the `CALL_RECORDS_INDEX_NAME` env var
-/// overrides this so local tests can point at a side alias pointing
-/// only at the join-shape index without disturbing the shared
-/// `call_records` alias.
-pub fn call_records_search_alias() -> &'static str {
- static NAME: OnceLock<&'static str> = OnceLock::new();
- NAME.get_or_init(|| match std::env::var("CALL_RECORDS_INDEX_NAME") {
- Ok(s) if !s.is_empty() => Box::leak(s.into_boxed_str()) as &'static str,
- _ => DEFAULT_CALL_RECORDS_ALIAS,
- })
-}
diff --git a/rust/cloud-storage/opensearch_client/src/chats_shape.rs b/rust/cloud-storage/opensearch_client/src/chats_shape.rs
deleted file mode 100644
index 892021d498..0000000000
--- a/rust/cloud-storage/opensearch_client/src/chats_shape.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-//! Dispatch helpers for the chats index migration from a flat
-//! one-doc-per-message shape to a parent/child join shape.
-//!
-//! Three dispatch points, mirroring [`crate::documents_shape`]:
-//!
-//! * `destination_uses_join_shape(dest)` — used by writers that take an
-//! explicit `index_override`. Returns `true` when the override names
-//! the join-shape physical index so the backfill can target it in
-//! join-shape mode while normal traffic continues writing flat docs
-//! through the alias.
-//!
-//! * `alias_uses_join_shape()` — used by callers that always target the
-//! `chats` alias (search reads, user-id deletes, title updates).
-//! Driven by the `CHATS_INDEX_USES_JOIN` env var so we can flip the
-//! alias contract atomically with the alias swap without per-call
-//! introspection.
-//!
-//! * `chats_search_alias()` — the alias name search reads target.
-//! Defaults to `chats`. The `CHATS_INDEX_NAME` env var overrides
-//! this so local end-to-end tests can read from a side alias pointing
-//! only at the join-shape index, without disturbing the shared
-//! `chats` alias on dev/prod.
-
-use std::sync::OnceLock;
-
-/// Physical name of the join-shape chats index. Used as the
-/// `index_override` value for backfills that should write in the join
-/// shape and as the trigger for `destination_uses_join_shape`.
-pub const CHATS_V2: &str = "chats_v2";
-
-/// Default alias name reads target. Production code always uses this.
-const DEFAULT_CHATS_ALIAS: &str = "chats";
-
-/// Whether writes targeting this destination should use the parent/child
-/// join shape.
-pub fn destination_uses_join_shape(destination: &str) -> bool {
- if destination == CHATS_V2 {
- return true;
- }
- if destination == DEFAULT_CHATS_ALIAS {
- return alias_uses_join_shape();
- }
- false
-}
-
-/// Whether the `chats` alias currently resolves to a join-shape index.
-///
-/// Controlled by the `CHATS_INDEX_USES_JOIN` env var, cached once per
-/// process. Operators set it `true` at the alias swap; before then it
-/// defaults to `false` so the existing flat-shape paths stay active.
-pub fn alias_uses_join_shape() -> bool {
- static ALIAS_USES_JOIN: OnceLock<bool> = OnceLock::new();
- *ALIAS_USES_JOIN.get_or_init(|| {
- std::env::var("CHATS_INDEX_USES_JOIN")
- .map(|v| v == "true")
- .unwrap_or(false)
- })
-}
-
-/// Alias name that search reads target for chats. Returns `chats` by
-/// default; the `CHATS_INDEX_NAME` env var overrides this so local
-/// tests can point at a side alias pointing only at the join-shape
-/// index without disturbing the shared `chats` alias.
-pub fn chats_search_alias() -> &'static str {
- static NAME: OnceLock<&'static str> = OnceLock::new();
- NAME.get_or_init(|| match std::env::var("CHATS_INDEX_NAME") {
- Ok(s) if !s.is_empty() => Box::leak(s.into_boxed_str()) as &'static str,
- _ => DEFAULT_CHATS_ALIAS,
- })
-}
diff --git a/rust/cloud-storage/opensearch_client/src/delete/document.rs b/rust/cloud-storage/opensearch_client/src/delete/document.rs
index 677c5ee5c1..7d15609b14 100644
--- a/rust/cloud-storage/opensearch_client/src/delete/document.rs
+++ b/rust/cloud-storage/opensearch_client/src/delete/document.rs
@@ -1,6 +1,6 @@
use models_opensearch::SearchIndex;
-use crate::{Result, documents_shape::alias_uses_join_shape, error::OpensearchClientError};
+use crate::{Result, error::OpensearchClientError};
/// Deletes all document nodes with the specified document_id
#[tracing::instrument(skip(client))]
@@ -60,40 +60,29 @@ pub async fn delete_document_by_id(
/// Deletes every document owned by `owner_id`.
///
-/// Flat shape: every chunk carries `owner_id`, so a simple term match
-/// catches them all. Join shape: only parents carry `owner_id`, so the
-/// query also matches children of those parents via `has_parent`.
+/// Only parent docs carry `owner_id`, so the query matches those parents
+/// directly and their child chunks via `has_parent`.
#[tracing::instrument(skip(client))]
pub async fn delete_document_by_owner_id(
client: &opensearch::OpenSearch,
owner_id: &str,
) -> Result<()> {
- let query = if alias_uses_join_shape() {
- serde_json::json!({
- "query": {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- { "term": { "owner_id": owner_id } },
- {
- "has_parent": {
- "parent_type": "document",
- "query": { "term": { "owner_id": owner_id } }
- }
+ let query = serde_json::json!({
+ "query": {
+ "bool": {
+ "minimum_should_match": 1,
+ "should": [
+ { "term": { "owner_id": owner_id } },
+ {
+ "has_parent": {
+ "parent_type": "document",
+ "query": { "term": { "owner_id": owner_id } }
}
- ]
- }
+ }
+ ]
}
- })
- } else {
- serde_json::json!({
- "query": {
- "term": {
- "owner_id": owner_id
- }
- }
- })
- };
+ }
+ });
let response = client
.delete_by_query(opensearch::DeleteByQueryParts::Index(&[
diff --git a/rust/cloud-storage/opensearch_client/src/documents_shape.rs b/rust/cloud-storage/opensearch_client/src/documents_shape.rs
deleted file mode 100644
index 0e00229b4f..0000000000
--- a/rust/cloud-storage/opensearch_client/src/documents_shape.rs
+++ /dev/null
@@ -1,76 +0,0 @@
-//! Dispatch helpers for the documents index migration from a flat-chunk
-//! shape to a parent/child join shape.
-//!
-//! Three dispatch points:
-//!
-//! * `destination_uses_join_shape(dest)` — used by writers that take an
-//! explicit `index_override`. Returns `true` when the override names
-//! the join-shape physical index so the backfill can target it in
-//! join-shape mode while normal traffic continues writing flat docs
-//! through the alias.
-//!
-//! * `alias_uses_join_shape()` — used by callers that always target the
-//! `documents` alias (search reads, owner-id deletes, metadata
-//! updates). Driven by the `DOCUMENTS_INDEX_USES_JOIN` env var so we
-//! can flip the alias contract atomically with the alias swap without
-//! per-call introspection.
-//!
-//! * `documents_search_alias()` — the alias name search reads target.
-//! Defaults to `documents`. The `DOCUMENTS_INDEX_NAME` env var
-//! overrides this so local end-to-end tests can read from a side
-//! alias pointing only at the join-shape index, without disturbing
-//! the shared `documents` alias on dev/prod.
-
-use std::sync::OnceLock;
-
-/// Physical name of the join-shape documents index. Used as the
-/// `index_override` value for backfills that should write in the join
-/// shape and as the trigger for `destination_uses_join_shape`.
-pub const DOCUMENTS_V2: &str = "documents_v2";
-
-/// Default alias name reads target. Production code always uses this.
-const DEFAULT_DOCUMENTS_ALIAS: &str = "documents";
-
-/// Whether writes targeting this destination should use the parent/child
-/// join shape. True when the destination is the explicit join-shape
-/// index name and, when configured via env var, when it's the
-/// `documents` alias too.
-pub fn destination_uses_join_shape(destination: &str) -> bool {
- if destination == DOCUMENTS_V2 {
- return true;
- }
- if destination == "documents" {
- return alias_uses_join_shape();
- }
- false
-}
-
-/// Whether the `documents` alias currently resolves to a join-shape index.
-///
-/// Controlled by the `DOCUMENTS_INDEX_USES_JOIN` env var, cached once per
-/// process. Operators set it `true` at the alias swap; before then it
-/// defaults to `false` so the existing flat-shape paths stay active.
-pub fn alias_uses_join_shape() -> bool {
- static ALIAS_USES_JOIN: OnceLock<bool> = OnceLock::new();
- *ALIAS_USES_JOIN.get_or_init(|| {
- std::env::var("DOCUMENTS_INDEX_USES_JOIN")
- .map(|v| v == "true")
- .unwrap_or(false)
- })
-}
-
-/// Alias name that search reads target for documents. Returns `documents`
-/// by default; the `DOCUMENTS_INDEX_NAME` env var overrides this so local
-/// tests can point at a side alias pointing only at the join-shape index
-/// without disturbing the shared `documents` alias.
-///
-/// Only the read path consults this — writes still resolve through
-/// `OpenSearchEntityType::Documents.index_name()` so the alias contract
-/// for ingestion stays unchanged.
-pub fn documents_search_alias() -> &'static str {
- static NAME: OnceLock<&'static str> = OnceLock::new();
- NAME.get_or_init(|| match std::env::var("DOCUMENTS_INDEX_NAME") {
- Ok(s) if !s.is_empty() => Box::leak(s.into_boxed_str()) as &'static str,
- _ => DEFAULT_DOCUMENTS_ALIAS,
- })
-}
diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rs
index 966b699fe8..516617dc29 100644
--- a/rust/cloud-storage/opensearch_client/src/lib.rs
+++ b/rust/cloud-storage/opensearch_client/src/lib.rs
@@ -1,8 +1,5 @@
-pub mod call_records_shape;
-pub mod chats_shape;
pub mod date_format;
pub mod delete;
-pub mod documents_shape;
pub mod error;
pub mod search;
pub mod unified;
diff --git a/rust/cloud-storage/opensearch_client/src/search/call_records.rs b/rust/cloud-storage/opensearch_client/src/search/call_records.rs
index ac556203f2..4c5a461e8d 100644
--- a/rust/cloud-storage/opensearch_client/src/search/call_records.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/call_records.rs
@@ -1,9 +1,7 @@
use std::collections::HashMap;
use crate::{
- Result,
- call_records_shape::{alias_uses_join_shape, call_records_search_alias},
- delegate_methods,
+ Result, delegate_methods,
search::{
builder::{SearchQueryBuilder, SearchQueryConfig},
model::{
@@ -40,19 +38,10 @@ const MATCH_PHRASE_PREFIX_MAX_EXPANSIONS: u32 = 256;
pub(crate) struct CallRecordIndex {
pub entity_id: uuid::Uuid,
pub channel_id: uuid::Uuid,
- /// Present on flat-shape (legacy) segment docs. Absent on join-shape
- /// parent docs — the matching segments come via `inner_hits`.
- #[serde(default)]
- pub transcript_id: Option<uuid::Uuid>,
#[serde(default)]
pub participant_ids: Vec<String>,
#[serde(default)]
pub channel_name: Option<String>,
- /// Present on flat-shape segment docs. Absent on join-shape parents.
- #[serde(default)]
- pub speaker_id: Option<String>,
- #[serde(default)]
- pub sequence_num: Option<i32>,
pub started_at_seconds: i64,
#[serde(default)]
pub ended_at_seconds: Option<i64>,
@@ -100,37 +89,12 @@ impl CallRecordQueryBuilder {
self
}
- pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- if alias_uses_join_shape() {
- return self.build_bool_query_join();
- }
- self.build_bool_query_flat()
- }
-
- /// Flat one-doc-per-segment path: the whole user query becomes a
- /// single phrase[-prefix] match on `content` and the channel /
- /// speaker filters sit on the same doc as the content.
- fn build_bool_query_flat<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- // Access comes from `ids_only` + accessible call_ids; these just narrow.
- let mut content_bool_query = self.inner.build_content_bool_query()?;
-
- if !self.channel_ids.is_empty() {
- content_bool_query.filter(QueryType::terms("channel_id", self.channel_ids.clone()));
- }
-
- if !self.speaker_ids.is_empty() {
- content_bool_query.filter(QueryType::terms("speaker_id", self.speaker_ids.clone()));
- }
-
- Ok(content_bool_query)
- }
-
- /// Parent/child join path: one `has_child` clause per term, ANDed
+ /// Parent/child join query: one `has_child` clause per term, ANDed
/// inside `bool.must` so every search term must match some segment
/// in the same call. channel_id lives on the parent so it sits on
/// `bool.filter` directly; speaker_id is child-side so it's a
/// has_child filter clause.
- fn build_bool_query_join<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
if self.inner.ids_only && self.inner.ids.is_empty() {
return Err(crate::error::OpensearchClientError::EmptyIdsWithIdsOnly(
CallRecordSearchConfig::ENTITY_INDEX,
@@ -142,11 +106,12 @@ impl CallRecordQueryBuilder {
let mut bool_query = BoolQueryBuilder::new();
- // Restrict to parent calls in the call_records alias (overridable
- // via CALL_RECORDS_INDEX_NAME for local end-to-end testing).
+ // Restrict to parent calls in the call_records alias.
bool_query.filter(QueryType::term(
"_index",
- call_records_search_alias().to_string(),
+ CallRecordSearchConfig::ENTITY_INDEX
+ .index_name()
+ .to_string(),
));
bool_query.filter(QueryType::term(
"call_relation",
diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rs
index 62ca76c83b..5a0cdf8e74 100644
--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs
@@ -1,9 +1,7 @@
use std::collections::HashMap;
use crate::{
- Result,
- chats_shape::{alias_uses_join_shape, chats_search_alias},
- delegate_methods,
+ Result, delegate_methods,
search::{
builder::{SearchQueryBuilder, SearchQueryConfig},
model::{Highlight, SearchGotoChat, SearchGotoContent, SearchHit, parse_highlight_hit},
@@ -40,15 +38,7 @@ const MATCH_PHRASE_PREFIX_MAX_EXPANSIONS: u32 = 256;
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct ChatIndex {
pub entity_id: uuid::Uuid,
- /// Present on flat-shape (legacy) message docs. Absent on join-shape
- /// parent docs — those carry chat-level metadata only and the
- /// matching message ids come via `inner_hits`.
- #[serde(default)]
- pub chat_message_id: Option<uuid::Uuid>,
pub user_id: String,
- /// Present on flat-shape message docs. Absent on join-shape parents.
- #[serde(default)]
- pub role: Option<String>,
pub title: String,
pub updated_at_seconds: Option<i64>,
}
@@ -91,32 +81,11 @@ impl ChatQueryBuilder {
self
}
- pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- if alias_uses_join_shape() {
- return self.build_bool_query_join();
- }
- self.build_bool_query_flat()
- }
-
- /// Flat one-doc-per-message path: the whole user query is a single
- /// phrase match on `content` and metadata filters sit on the same
- /// doc as the content.
- fn build_bool_query_flat<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- let mut content_bool_query = self.inner.build_content_bool_query()?;
-
- if !self.role.is_empty() {
- let should_query = should_wildcard_field_query_builder("role", &self.role);
- content_bool_query.filter(should_query);
- }
-
- Ok(content_bool_query)
- }
-
- /// Parent/child join path: one `has_child` clause per term, ANDed
+ /// Parent/child join query: one `has_child` clause per term, ANDed
/// inside `bool.must` so each term must match some message in the
/// same chat. Parent metadata filters (user, ids) sit on
/// `bool.filter` because they live on the parent doc.
- fn build_bool_query_join<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
if self.inner.ids_only && self.inner.ids.is_empty() {
return Err(crate::error::OpensearchClientError::EmptyIdsWithIdsOnly(
ChatSearchConfig::ENTITY_INDEX,
@@ -128,10 +97,11 @@ impl ChatQueryBuilder {
let mut bool_query = BoolQueryBuilder::new();
- // Restrict to parent chats in the chats alias (overridable via
- // CHATS_INDEX_NAME for local end-to-end testing against a side
- // alias).
- bool_query.filter(QueryType::term("_index", chats_search_alias().to_string()));
+ // Restrict to parent chats in the chats alias.
+ bool_query.filter(QueryType::term(
+ "_index",
+ ChatSearchConfig::ENTITY_INDEX.index_name().to_string(),
+ ));
bool_query.filter(QueryType::term(
"chat_relation",
PARENT_RELATION.to_string(),
diff --git a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs b/rust/cloud-storage/opensearch_client/src/search/chats/test.rs
index 7223fd8c16..dd8e7412e0 100644
--- a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/chats/test.rs
@@ -2,7 +2,7 @@ use super::*;
use opensearch_query_builder::ToOpenSearchJson;
#[test]
-fn test_build_bool_query() -> anyhow::Result<()> {
+fn test_build_bool_query_join_shape() -> anyhow::Result<()> {
let builder = ChatQueryBuilder::new(vec!["test".to_string()])
.match_type("exact")
.page_size(20)
@@ -12,45 +12,59 @@ fn test_build_bool_query() -> anyhow::Result<()> {
.ids(vec!["chat1".to_string(), "chat2".to_string()])
.role(vec!["user".to_string(), "assistant".to_string()]);
- let result = builder.build_bool_query()?;
+ let json = builder.build_bool_query()?.build().to_json();
- let expected = serde_json::json!({
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {"terms": {"entity_id": ["chat1", "chat2"]}},
- {"term": {"user_id": "user123"}}
- ]
- }
- },
- {"term": {"_index": "chats"}},
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {"wildcard": {"role": {"case_insensitive": true, "value": "*user*"}}},
- {"wildcard": {"role": {"case_insensitive": true, "value": "*assistant*"}}}
- ]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {"match_phrase": {"content": "test"}}
- ]
- }
- }
- ]
- }
- });
+ let filter = json["bool"]["filter"].as_array().expect("filter array");
+ assert!(
+ filter.contains(&serde_json::json!({"term": {"_index": "chats"}})),
+ "filter must constrain to chats index: {filter:?}"
+ );
+ assert!(
+ filter.contains(&serde_json::json!({"term": {"chat_relation": "chat"}})),
+ "filter must constrain to parent chats: {filter:?}"
+ );
+ assert!(
+ filter.contains(&serde_json::json!({
+ "bool": {
+ "minimum_should_match": 1,
+ "should": [
+ {"terms": {"entity_id": ["chat1", "chat2"]}},
+ {"term": {"user_id": "user123"}}
+ ]
+ }
+ })),
+ "filter must constrain to ids or owner: {filter:?}"
+ );
- assert_eq!(result.build().to_json(), expected);
+ let must = json["bool"]["must"].as_array().expect("must array");
+ assert_eq!(must.len(), 1, "expected one has_child per term: {must:?}");
+
+ let has_child = &must[0]["has_child"];
+ assert_eq!(has_child["type"], "message");
+ assert_eq!(has_child["inner_hits"]["name"], "term_0");
+
+ // role is a child-side field: it must sit inside the has_child query
+ // alongside the term match, so the same message that matches the term
+ // is also from one of the requested roles.
+ let inner_must = has_child["query"]["bool"]["must"]
+ .as_array()
+ .expect("has_child query must array");
+ assert!(
+ inner_must.contains(&serde_json::json!({"match_phrase": {"content": "test"}})),
+ "has_child query must match the term: {inner_must:?}"
+ );
+ assert!(
+ inner_must.contains(&serde_json::json!({
+ "bool": {
+ "minimum_should_match": 1,
+ "should": [
+ {"wildcard": {"role": {"case_insensitive": true, "value": "*user*"}}},
+ {"wildcard": {"role": {"case_insensitive": true, "value": "*assistant*"}}}
+ ]
+ }
+ })),
+ "has_child query must filter on role: {inner_must:?}"
+ );
Ok(())
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rs
index 8433b69060..d9e30373e4 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs
@@ -2,7 +2,6 @@ use std::collections::HashMap;
use crate::{
Result, delegate_methods,
- documents_shape::{alias_uses_join_shape, documents_search_alias},
search::{
builder::{SearchQueryBuilder, SearchQueryConfig},
model::{Highlight, SearchGotoContent, SearchGotoDocument, SearchHit, parse_highlight_hit},
@@ -77,34 +76,11 @@ impl DocumentQueryBuilder {
self
}
- pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- if alias_uses_join_shape() {
- return self.build_bool_query_join();
- }
- self.build_bool_query_flat()
- }
-
- /// Flat-chunk path: every chunk is its own top-level OpenSearch doc
- /// and the whole user query becomes a single phrase[-prefix] match
- /// on `content`.
- fn build_bool_query_flat<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- let mut query = self.inner.build_content_bool_query()?;
-
- if !self.sub_types.is_empty() {
- query.filter(QueryType::terms(
- "sub_type".to_string(),
- self.sub_types.clone(),
- ));
- }
-
- Ok(query)
- }
-
- /// Parent/child join path: one `has_child` clause per term, ANDed
+ /// Parent/child join query: one `has_child` clause per term, ANDed
/// inside `bool.must`. Parent metadata filters (owner, ids,
/// sub_type) sit on `bool.filter` directly because they live on
/// the parent doc.
- fn build_bool_query_join<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
if self.inner.ids_only && self.inner.ids.is_empty() {
return Err(crate::error::OpensearchClientError::EmptyIdsWithIdsOnly(
DocumentSearchConfig::ENTITY_INDEX,
@@ -116,12 +92,10 @@ impl DocumentQueryBuilder {
let mut bool_query = BoolQueryBuilder::new();
- // Restrict to parent documents in the documents alias (overridable
- // via DOCUMENTS_INDEX_NAME for local end-to-end testing against a
- // side alias).
+ // Restrict to parent documents in the documents alias.
bool_query.filter(QueryType::term(
"_index",
- documents_search_alias().to_string(),
+ DocumentSearchConfig::ENTITY_INDEX.index_name().to_string(),
));
bool_query.filter(QueryType::term(
"document_relation",
@@ -253,8 +227,6 @@ fn build_child_content_query<'a>(term: &str, match_type: &str) -> QueryType<'a>
pub(crate) struct DocumentIndex {
pub entity_id: uuid::Uuid,
pub document_name: String,
- pub node_id: Option<String>,
- pub raw_content: Option<String>,
pub owner_id: String,
pub file_type: String,
pub updated_at_seconds: Option<i64>,
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
index 00000d9c53..68e65fe0f2 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
@@ -1,55 +1,6 @@
use super::*;
use opensearch_query_builder::ToOpenSearchJson;
-// `build_bool_query` dispatches on `alias_uses_join_shape()`, which is
-// cached via OnceLock for the process lifetime — so tests call the
-// explicit flat/join variants directly to stay deterministic regardless
-// of env state.
-
-#[test]
-fn test_build_bool_query_flat_shape() -> anyhow::Result<()> {
- let builder = DocumentQueryBuilder::new(vec!["test".to_string()])
- .match_type("exact")
- .page_size(20)
- .page(1)
- .user_id("user123")
- .collapse(true)
- .ids(vec!["doc1".to_string(), "doc2".to_string()]);
-
- let result = builder.build_bool_query_flat()?;
-
- let expected = serde_json::json!({
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {"terms": {"entity_id": ["doc1", "doc2"]}},
- {"term": {"owner_id": "user123"}}
- ]
- }
- },
- {"term": {"_index": "documents"}}
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {"match_phrase": {"content": "test"}}
- ]
- }
- }
- ]
- }
- });
-
- assert_eq!(result.build().to_json(), expected);
-
- Ok(())
-}
-
#[test]
fn test_build_bool_query_join_shape_multi_term_and() -> anyhow::Result<()> {
let builder = DocumentQueryBuilder::new(vec!["foo".to_string(), "bar".to_string()])
@@ -58,7 +9,7 @@ fn test_build_bool_query_join_shape_multi_term_and() -> anyhow::Result<()> {
.page(0)
.user_id("alice");
- let json = builder.build_bool_query_join()?.build().to_json();
+ let json = builder.build_bool_query()?.build().to_json();
let filter = json["bool"]["filter"].as_array().expect("filter array");
assert!(
@@ -99,7 +50,7 @@ fn test_build_bool_query_join_shape_quoted_phrase_uses_match_phrase() -> anyhow:
.match_type("partial")
.user_id("alice");
- let json = builder.build_bool_query_join()?.build().to_json();
+ let json = builder.build_bool_query()?.build().to_json();
let must = &json["bool"]["must"][0]["has_child"]["query"];
assert!(
must.get("match_phrase").is_some(),
@@ -115,7 +66,7 @@ fn test_build_bool_query_join_shape_short_term_no_prefix() -> anyhow::Result<()>
.match_type("partial")
.user_id("alice");
- let json = builder.build_bool_query_join()?.build().to_json();
+ let json = builder.build_bool_query()?.build().to_json();
let must = &json["bool"]["must"][0]["has_child"]["query"];
assert!(
must.get("match_phrase").is_some(),
@@ -130,7 +81,7 @@ fn test_build_bool_query_join_shape_exact_match_type_uses_match_phrase() -> anyh
.match_type("exact")
.user_id("alice");
- let json = builder.build_bool_query_join()?.build().to_json();
+ let json = builder.build_bool_query()?.build().to_json();
let must = &json["bool"]["must"][0]["has_child"]["query"];
assert!(
must.get("match_phrase").is_some(),
@@ -147,7 +98,7 @@ fn test_build_bool_query_join_shape_ids_only_filter() -> anyhow::Result<()> {
.ids(vec!["doc1".to_string(), "doc2".to_string()])
.ids_only(true);
- let json = builder.build_bool_query_join()?.build().to_json();
+ let json = builder.build_bool_query()?.build().to_json();
let filter = json["bool"]["filter"].as_array().expect("filter array");
assert!(
filter.contains(&serde_json::json!({
@@ -171,7 +122,7 @@ fn test_build_bool_query_join_shape_sub_type_filter() -> anyhow::Result<()> {
.user_id("alice")
.sub_types(vec!["task".to_string()]);
- let json = builder.build_bool_query_join()?.build().to_json();
+ let json = builder.build_bool_query()?.build().to_json();
let filter = json["bool"]["filter"].as_array().expect("filter array");
assert!(
filter.contains(&serde_json::json!({"terms": {"sub_type": ["task"]}})),
@@ -186,7 +137,7 @@ fn test_build_bool_query_join_shape_has_inner_hits() -> anyhow::Result<()> {
.match_type("partial")
.user_id("alice");
- let json = builder.build_bool_query_join()?.build().to_json();
+ let json = builder.build_bool_query()?.build().to_json();
let must = json["bool"]["must"].as_array().expect("must array");
for (idx, clause) in must.iter().enumerate() {
let inner = &clause["has_child"]["inner_hits"];
@@ -204,11 +155,11 @@ fn test_build_bool_query_join_shape_has_inner_hits() -> anyhow::Result<()> {
}
#[test]
-fn document_index_deserializes_parent_shape_with_no_node_id_or_raw_content() {
- // Join-shape parent docs only carry parent metadata in `_source`;
- // `node_id` and `raw_content` are child-only fields and are
- // absent. Deserialization has to succeed (otherwise the unified
- // search response 500s on any v2 hit) and produce None for both.
+fn document_index_deserializes_parent_shape() {
+ // Parent docs carry only parent-level metadata in `_source`; the
+ // matching chunks' node_id / raw_content come via `inner_hits`.
+ // Deserialization has to succeed (otherwise the unified search
+ // response 500s on any parent hit).
let parent = serde_json::json!({
"entity_id": "00000000-0000-0000-0000-000000000001",
"document_name": "Q3 Planning",
@@ -220,28 +171,6 @@ fn document_index_deserializes_parent_shape_with_no_node_id_or_raw_content() {
let doc: DocumentIndex =
serde_json::from_value(parent).expect("parent _source should deserialize");
- assert!(doc.node_id.is_none(), "parent shape should have no node_id");
- assert!(
- doc.raw_content.is_none(),
- "parent shape should have no raw_content"
- );
-}
-
-#[test]
-fn document_index_deserializes_flat_chunk_shape_with_node_id() {
- // Flat-shape chunk docs carry node_id (and optionally raw_content)
- // directly. Make sure they keep deserializing after the move to
- // Option<String>.
- let chunk = serde_json::json!({
- "entity_id": "00000000-0000-0000-0000-000000000001",
- "document_name": "Q3 Planning",
- "node_id": "0",
- "owner_id": "macro|[email protected]",
- "file_type": "pdf",
- "content": "Page text",
- "updated_at_seconds": 1779000000_i64,
- });
-
- let doc: DocumentIndex = serde_json::from_value(chunk).expect("flat chunk should deserialize");
- assert_eq!(doc.node_id.as_deref(), Some("0"));
+ assert_eq!(doc.document_name, "Q3 Planning");
+ assert_eq!(doc.owner_id, "macro|[email protected]");
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index 92537d3925..4d35224369 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -282,11 +282,11 @@ where
/// Expand one OpenSearch hit into one or more `SearchHit`s.
///
-/// For join-shape parents (documents, chats), OpenSearch returns one
-/// parent hit per matching root with the matching children nested
-/// under `inner_hits`. Each entity's search module knows how to unpack
-/// those into child-level hits; everything else (flat indices) takes
-/// the 1:1 conversion.
+/// For join-shape parents (documents, chats, call records), OpenSearch
+/// returns one parent hit per matching root with the matching children
+/// nested under `inner_hits`. Each entity's search module knows how to
+/// unpack those into child-level hits; everything else (channels,
+/// emails) takes the 1:1 conversion.
fn expand_hit_into_search_hits(hit: Hit<UnifiedSearchIndex>) -> Vec<SearchHit> {
match &hit.source {
UnifiedSearchIndex::Document(parent) => {
@@ -383,13 +383,12 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
})
.unwrap_or_default(),
goto: Some(SearchGotoContent::Documents(SearchGotoDocument {
- // Parent hits in the join shape have no node_id on
- // `_source` (it lives on the matching chunk in
- // inner_hits). Fall back to empty for now; piping
- // the chunk's node_id through inner_hits is a
- // follow-up.
- node_id: a.node_id.unwrap_or_default(),
- raw_content: a.raw_content,
+ // Reached only on the defensive parent fallback when a
+ // matched parent carried no inner_hits. node_id and
+ // raw_content are child-only fields, so there is no
+ // chunk-level identifier to navigate to here.
+ node_id: String::new(),
+ raw_content: None,
})),
updated_at: a
.updated_at_seconds
@@ -446,13 +445,12 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
})
.unwrap_or_default(),
goto: Some(SearchGotoContent::Chats(SearchGotoChat {
- // Flat-shape docs always carry chat_message_id +
- // role; the join-shape parent fallback path can
- // arrive here only when inner_hits was empty, in
- // which case we have no message-level identifier
- // to navigate to.
- chat_message_id: a.chat_message_id.unwrap_or_default(),
- role: a.role.unwrap_or_default(),
+ // Reached only on the defensive parent fallback when a
+ // matched parent carried no inner_hits. chat_message_id
+ // and role are child-only fields, so there is no
+ // message-level identifier to navigate to here.
+ chat_message_id: uuid::Uuid::nil(),
+ role: String::new(),
})),
updated_at: a
.updated_at_seconds
@@ -476,13 +474,13 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
.unwrap_or_default(),
goto: Some(SearchGotoContent::CallRecords(SearchGotoCallRecord {
channel_id: a.channel_id,
- // Flat-shape docs always carry transcript/speaker/sequence;
- // the join-shape parent fallback path only arrives here
- // when inner_hits was empty, in which case we have no
- // segment-level identifier to navigate to.
- transcript_id: a.transcript_id.unwrap_or_default(),
- speaker_id: a.speaker_id.unwrap_or_default(),
- sequence_num: a.sequence_num.unwrap_or_default(),
+ // Reached only on the defensive parent fallback when a
+ // matched parent carried no inner_hits. transcript_id,
+ // speaker_id, and sequence_num are child-only fields, so
+ // there is no segment-level identifier to navigate to here.
+ transcript_id: uuid::Uuid::nil(),
+ speaker_id: String::new(),
+ sequence_num: 0,
started_at: DateTime::from_timestamp(a.started_at_seconds, 0)
.unwrap_or_default(),
ended_at: a
@@ -621,22 +619,7 @@ pub(crate) async fn search_unified(
tracing::trace!("search request {:?}", search_request);
- // Documents, chats, and call records reads can be redirected to a
- // side alias via DOCUMENTS_INDEX_NAME / CHATS_INDEX_NAME /
- // CALL_RECORDS_INDEX_NAME for local end-to-end testing; every other
- // entity type keeps its default alias.
- let search_indices: Vec<&str> = args
- .search_indices
- .iter()
- .map(|i| match i {
- OpenSearchEntityType::Documents => crate::documents_shape::documents_search_alias(),
- OpenSearchEntityType::Chats => crate::chats_shape::chats_search_alias(),
- OpenSearchEntityType::CallRecords => {
- crate::call_records_shape::call_records_search_alias()
- }
- other => other.index_name(),
- })
- .collect();
+ let search_indices: Vec<&str> = args.search_indices.iter().map(|i| i.index_name()).collect();
let response = async {
client
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
index a114c11816..ec1217da33 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -459,6 +459,22 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
let result = build_unified_search_request(&unified_search_args)?;
+ // Documents and chats are join-shape (has_child); compute their
+ // sub-queries from the builders rather than inlining the has_child
+ // JSON. Emails and channels are flat and stay inline below.
+ let doc_should = QueryType::from(
+ DocumentQueryBuilder::from(DocumentSearchArgs::from(unified_search_args.clone()))
+ .build_bool_query()?
+ .build(),
+ )
+ .to_json();
+ let chat_should = QueryType::from(
+ ChatQueryBuilder::from(ChatSearchArgs::from(unified_search_args.clone()))
+ .build_bool_query()?
+ .build(),
+ )
+ .to_json();
+
let expected = serde_json::json!({
"collapse": {
"field": "entity_id"
@@ -482,48 +498,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
"bool": {
"minimum_should_match": 1,
"should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "owner_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "documents"
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
+ doc_should,
{
"bool": {
"filter": [
@@ -717,71 +692,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
]
}
},
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "chats"
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "role": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "role": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- }
+ chat_should
]
}
},
@@ -870,6 +781,16 @@ fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
};
let result = build_unified_search_request(&unified_search_args)?;
+
+ // Documents are join-shape (has_child); compute the sub-query from the
+ // builder rather than inlining the has_child JSON.
+ let doc_should = QueryType::from(
+ DocumentQueryBuilder::from(DocumentSearchArgs::from(unified_search_args.clone()))
+ .build_bool_query()?
+ .build(),
+ )
+ .to_json();
+
let expected = serde_json::json!(
{
"collapse": {
@@ -894,48 +815,7 @@ fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
"bool": {
"minimum_should_match": 1,
"should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "owner_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "documents"
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- }
+ doc_should
]
}
},
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs b/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs
index 89a7e95be5..ffe93c9898 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs
@@ -3,10 +3,7 @@ use std::collections::HashSet;
use models_opensearch::SearchIndex;
use super::BulkUpsertResult;
-use crate::{
- Result, call_records_shape::destination_uses_join_shape, date_format::EpochSeconds,
- error::OpensearchClientError,
-};
+use crate::{Result, date_format::EpochSeconds};
/// Relation name for parent docs in the call_records join field.
const PARENT_RELATION: &str = "call";
@@ -42,55 +39,9 @@ pub(crate) async fn upsert_call_record_segment(
index_override: Option<&str>,
) -> Result<()> {
let destination = resolve_destination(index_override);
- if destination_uses_join_shape(destination) {
- return bulk_upsert_call_record_segments_join(
- client,
- std::slice::from_ref(args),
- destination,
- )
+ bulk_upsert_call_record_segments_inner(client, std::slice::from_ref(args), destination)
.await
- .map(|_| ());
- }
- upsert_call_record_segment_flat(client, args, destination).await
-}
-
-async fn upsert_call_record_segment_flat(
- client: &opensearch::OpenSearch,
- args: &UpsertCallRecordSegmentArgs,
- index: &str,
-) -> Result<()> {
- let id = &args.transcript_id;
- let response = client
- .index(opensearch::IndexParts::IndexId(index, id))
- .body(args)
- .send()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_call_record_segment".to_string()),
- })?;
-
- let status_code = response.status_code();
- if status_code.is_success() {
- tracing::trace!(id=%id, "call record segment upserted");
- return Ok(());
- }
-
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_call_record_segment".to_string()),
- })?;
-
- tracing::error!(status_code=%status_code, body=%body, "error upserting call record segment");
-
- Err(OpensearchClientError::Unknown {
- details: body,
- method: Some("upsert_call_record_segment".to_string()),
- })
+ .map(|_| ())
}
#[tracing::instrument(skip(client, segments), err)]
@@ -104,32 +55,7 @@ pub(crate) async fn bulk_upsert_call_record_segments(
}
let index = resolve_destination(index_override);
- if destination_uses_join_shape(index) {
- bulk_upsert_call_record_segments_join(client, segments, index).await
- } else {
- bulk_upsert_call_record_segments_flat(client, segments, index).await
- }
-}
-
-async fn bulk_upsert_call_record_segments_flat(
- client: &opensearch::OpenSearch,
- segments: &[UpsertCallRecordSegmentArgs],
- index: &str,
-) -> Result<BulkUpsertResult> {
- let mut bulk_body = Vec::with_capacity(segments.len() * 2);
-
- for seg in segments {
- let action = serde_json::json!({ "index": { "_id": seg.transcript_id } });
- bulk_body.push(action.to_string());
- bulk_body.push(serde_json::to_string(seg).map_err(|e| {
- OpensearchClientError::DeserializationFailed {
- details: e.to_string(),
- method: Some("bulk_upsert_call_record_segments".to_string()),
- }
- })?);
- }
-
- super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_call_record_segments").await
+ bulk_upsert_call_record_segments_inner(client, segments, index).await
}
/// Builds the JSON document body for the parent call doc.
@@ -170,7 +96,7 @@ fn child_doc_body(seg: &UpsertCallRecordSegmentArgs) -> serde_json::Value {
/// Writes one parent call doc per unique call_id and one child segment
/// doc per row, all rooted at the call_id via `_routing` so the parent
/// and all its segments live on the same shard.
-async fn bulk_upsert_call_record_segments_join(
+async fn bulk_upsert_call_record_segments_inner(
client: &opensearch::OpenSearch,
segments: &[UpsertCallRecordSegmentArgs],
index: &str,
@@ -201,7 +127,7 @@ async fn bulk_upsert_call_record_segments_join(
client,
index,
bulk_body,
- "bulk_upsert_call_record_segments_join",
+ "bulk_upsert_call_record_segments_inner",
)
.await
}
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs b/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
index c0cebaa668..372e0c46c8 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
@@ -1,11 +1,6 @@
use models_opensearch::SearchIndex;
-use crate::{
- Result,
- chats_shape::{alias_uses_join_shape, destination_uses_join_shape},
- date_format::EpochSeconds,
- error::OpensearchClientError,
-};
+use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};
/// Relation name for parent docs in the chats join field.
const PARENT_RELATION: &str = "chat";
@@ -40,71 +35,6 @@ fn resolve_destination(index_override: Option<&str>) -> &str {
index_override.unwrap_or(SearchIndex::Chats.as_ref())
}
-#[tracing::instrument(skip(client))]
-pub(crate) async fn upsert_chat_message(
- client: &opensearch::OpenSearch,
- args: &UpsertChatMessageArgs,
- index_override: Option<&str>,
-) -> Result<()> {
- let destination = resolve_destination(index_override);
- if destination_uses_join_shape(destination) {
- upsert_chat_message_join(client, args, destination).await
- } else {
- upsert_chat_message_flat(client, args, destination).await
- }
-}
-
-// ---------------------------------------------------------------------------
-// Flat-shape (legacy) path
-// ---------------------------------------------------------------------------
-
-async fn upsert_chat_message_flat(
- client: &opensearch::OpenSearch,
- args: &UpsertChatMessageArgs,
- index: &str,
-) -> Result<()> {
- let id = format!("{}:{}", args.chat_id, args.chat_message_id);
- let response = client
- .index(opensearch::IndexParts::IndexId(index, &id))
- .body(args)
- .send()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_chat_message".to_string()),
- })?;
-
- let status_code = response.status_code();
- if status_code.is_success() {
- tracing::trace!(id=%id, "chat message upserted successfully");
- return Ok(());
- }
-
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_chat_message".to_string()),
- })?;
-
- tracing::error!(
- status_code=%status_code,
- body=%body,
- "error upserting chat message",
- );
-
- Err(OpensearchClientError::Unknown {
- details: body,
- method: Some("upsert_chat_message".to_string()),
- })
-}
-
-// ---------------------------------------------------------------------------
-// Join-shape path
-// ---------------------------------------------------------------------------
-
/// Builds the JSON document body for the parent chat doc.
fn parent_doc_body(args: &UpsertChatMessageArgs) -> serde_json::Value {
serde_json::json!({
@@ -136,11 +66,13 @@ fn child_doc_body(args: &UpsertChatMessageArgs) -> serde_json::Value {
/// the chat_id via `_routing` so they live on the same shard. Uses
/// full-overwrite `index` semantics (not `update + doc_as_upsert`) so
/// stale optional fields can't leak across writes.
-async fn upsert_chat_message_join(
+#[tracing::instrument(skip(client))]
+pub(crate) async fn upsert_chat_message(
client: &opensearch::OpenSearch,
args: &UpsertChatMessageArgs,
- index: &str,
+ index_override: Option<&str>,
) -> Result<()> {
+ let index = resolve_destination(index_override);
let routing = args.chat_id.as_str();
let parent_body = parent_doc_body(args);
@@ -152,7 +84,7 @@ async fn upsert_chat_message_join(
.await
.map_err(|err| OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("upsert_chat_message_join_parent".to_string()),
+ method: Some("upsert_chat_message_parent".to_string()),
})?;
if !parent_response.status_code().is_success() {
@@ -160,7 +92,7 @@ async fn upsert_chat_message_join(
let body = parent_response.text().await.map_err(|err| {
OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("upsert_chat_message_join_parent".to_string()),
+ method: Some("upsert_chat_message_parent".to_string()),
}
})?;
tracing::error!(
@@ -170,7 +102,7 @@ async fn upsert_chat_message_join(
);
return Err(OpensearchClientError::Unknown {
details: body,
- method: Some("upsert_chat_message_join_parent".to_string()),
+ method: Some("upsert_chat_message_parent".to_string()),
});
}
@@ -184,31 +116,31 @@ async fn upsert_chat_message_join(
.await
.map_err(|err| OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("upsert_chat_message_join_child".to_string()),
+ method: Some("upsert_chat_message_child".to_string()),
})?;
let status_code = child_response.status_code();
if status_code.is_success() {
- tracing::trace!(id=%child_id, "chat message upserted successfully (join)");
+ tracing::trace!(id=%child_id, "chat message upserted successfully");
return Ok(());
}
let body = child_response.text().await.map_err(|err| {
OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("upsert_chat_message_join_child".to_string()),
+ method: Some("upsert_chat_message_child".to_string()),
}
})?;
tracing::error!(
status_code=%status_code,
body=%body,
- "error upserting chat message (join)",
+ "error upserting chat message",
);
Err(OpensearchClientError::Unknown {
details: body,
- method: Some("upsert_chat_message_join_child".to_string()),
+ method: Some("upsert_chat_message_child".to_string()),
})
}
@@ -216,28 +148,13 @@ async fn upsert_chat_message_join(
// Chat metadata updates
// ---------------------------------------------------------------------------
-/// Updates the chat metadata for all chat messages.
-///
-/// On the join shape, title lives only on the parent doc so this is a
-/// single update by id. On the flat shape, title is denormalized across
-/// every message doc so we update by query.
+/// Updates the chat metadata for a chat. Title lives only on the parent
+/// doc so this is a single update by id, routed to the parent's shard.
#[tracing::instrument(skip(client))]
pub(crate) async fn update_chat_metadata(
client: &opensearch::OpenSearch,
chat_id: &str,
title: &str,
-) -> Result<()> {
- if alias_uses_join_shape() {
- update_chat_metadata_join(client, chat_id, title).await
- } else {
- update_chat_metadata_flat(client, chat_id, title).await
- }
-}
-
-async fn update_chat_metadata_join(
- client: &opensearch::OpenSearch,
- chat_id: &str,
- title: &str,
) -> Result<()> {
use opensearch::UpdateParts;
use serde_json::json;
@@ -252,7 +169,7 @@ async fn update_chat_metadata_join(
.await
.map_err(|err| OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("update_chat_metadata_join".to_string()),
+ method: Some("update_chat_metadata".to_string()),
})?;
let status_code = response.status_code();
@@ -260,7 +177,7 @@ async fn update_chat_metadata_join(
tracing::debug!(
chat_id=%chat_id,
title=%title,
- "chat metadata updated successfully (join)"
+ "chat metadata updated successfully"
);
return Ok(());
}
@@ -271,94 +188,18 @@ async fn update_chat_metadata_join(
.await
.map_err(|err| OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("update_chat_metadata_join".to_string()),
+ method: Some("update_chat_metadata".to_string()),
})?;
tracing::error!(
status_code=?status_code,
body=?body,
chat_id=%chat_id,
- "error updating chat metadata (join)",
+ "error updating chat metadata",
);
Err(OpensearchClientError::Unknown {
details: body,
- method: Some("update_chat_metadata_join".to_string()),
+ method: Some("update_chat_metadata".to_string()),
})
}
-
-async fn update_chat_metadata_flat(
- client: &opensearch::OpenSearch,
- chat_id: &str,
- title: &str,
-) -> Result<()> {
- use opensearch::UpdateByQueryParts;
- use serde_json::json;
-
- let query = json!({
- "query": {
- "term": {
- "entity_id": chat_id
- }
- },
- "script": {
- "source": "ctx._source.title = params.title",
- "params": {
- "title": title
- }
- }
- });
-
- let response = client
- .update_by_query(UpdateByQueryParts::Index(&[SearchIndex::Chats.as_ref()]))
- .body(query)
- .send()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("update_chat_metadata".to_string()),
- })?;
-
- let status_code = response.status_code();
- if status_code.is_success() {
- let response_body: serde_json::Value =
- response
- .json()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("update_chat_metadata".to_string()),
- })?;
-
- let updated_count = response_body["updated"].as_u64().unwrap_or(0);
- tracing::debug!(
- chat_id=%chat_id,
- title=%title,
- updated_count=%updated_count,
- "chat metadata updated successfully"
- );
- } else {
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("update_chat_metadata".to_string()),
- })?;
-
- tracing::error!(
- status_code=?status_code,
- body=?body,
- chat_id=%chat_id,
- "error updating chat metadata",
- );
-
- return Err(OpensearchClientError::Unknown {
- details: body,
- method: Some("update_chat_metadata".to_string()),
- });
- }
-
- Ok(())
-}
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document.rs b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
index 8f461b9ddd..ab2907fa97 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/document.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
@@ -3,12 +3,7 @@ use std::collections::HashSet;
use models_opensearch::SearchIndex;
use super::BulkUpsertResult;
-use crate::{
- Result,
- date_format::EpochSeconds,
- documents_shape::{alias_uses_join_shape, destination_uses_join_shape},
- error::OpensearchClientError,
-};
+use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};
/// Relation name for parent docs in the join field.
const PARENT_RELATION: &str = "document";
@@ -53,55 +48,6 @@ fn resolve_destination(index_override: Option<&str>) -> &str {
index_override.unwrap_or(SearchIndex::Documents.as_ref())
}
-// ---------------------------------------------------------------------------
-// Flat-shape (legacy) path
-// ---------------------------------------------------------------------------
-
-/// Process a single chunk of documents in the legacy flat shape.
-async fn bulk_upsert_single_chunk_flat(
- client: &opensearch::OpenSearch,
- documents: &[UpsertDocumentArgs],
- index: &str,
-) -> Result<BulkUpsertResult> {
- let mut bulk_body = Vec::new();
-
- for doc in documents {
- let id = format!("{}:{}", doc.document_id, doc.node_id);
-
- let action = serde_json::json!({
- "index": {
- "_id": id
- }
- });
-
- bulk_body.push(action.to_string());
- bulk_body.push(serde_json::to_string(doc).map_err(|e| {
- OpensearchClientError::DeserializationFailed {
- details: e.to_string(),
- method: Some("bulk_upsert_single_chunk_flat".to_string()),
- }
- })?);
- }
-
- let result =
- super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_single_chunk_flat")
- .await?;
-
- tracing::trace!(
- chunk_total = documents.len(),
- successful = result.successful,
- failed = result.failed,
- version_conflicts = result.version_conflicts,
- "bulk upsert chunk completed (flat)"
- );
-
- Ok(result)
-}
-
-// ---------------------------------------------------------------------------
-// Join-shape path
-// ---------------------------------------------------------------------------
-
/// Builds the JSON document body for a parent doc, given any one
/// `UpsertDocumentArgs` belonging to that parent (parent metadata is
/// denormalized identically across all chunks of the same document, so any
@@ -138,7 +84,7 @@ fn child_doc_body(chunk: &UpsertDocumentArgs) -> serde_json::Value {
doc
}
-/// Process a single chunk of documents in the join shape.
+/// Process a single chunk of documents.
///
/// Emits, for each chunk:
/// - one parent `index` op with `routing = parent_id` (deduped within
@@ -150,7 +96,7 @@ fn child_doc_body(chunk: &UpsertDocumentArgs) -> serde_json::Value {
/// Cross-batch duplicate parent writes are accepted as cheap last-writer-
/// wins overwrites; all writers should agree on parent metadata since it's
/// denormalized from the same source.
-async fn bulk_upsert_single_chunk_join(
+async fn bulk_upsert_single_chunk(
client: &opensearch::OpenSearch,
documents: &[UpsertDocumentArgs],
index: &str,
@@ -185,8 +131,7 @@ async fn bulk_upsert_single_chunk_join(
}
let result =
- super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_single_chunk_join")
- .await?;
+ super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_single_chunk").await?;
tracing::trace!(
chunk_total = documents.len(),
@@ -194,14 +139,14 @@ async fn bulk_upsert_single_chunk_join(
successful = result.successful,
failed = result.failed,
version_conflicts = result.version_conflicts,
- "bulk upsert chunk completed (join)"
+ "bulk upsert chunk completed"
);
Ok(result)
}
// ---------------------------------------------------------------------------
-// Public entry points (dispatch)
+// Public entry points
// ---------------------------------------------------------------------------
/// Bulk upsert documents to reduce version conflicts with automatic chunking
@@ -219,7 +164,6 @@ pub(crate) async fn bulk_upsert_documents(
let mut overall_result = BulkUpsertResult::default();
let index = resolve_destination(index_override);
- let join_shape = destination_uses_join_shape(index);
let chunks: Vec<_> = documents.chunks(CHUNK_SIZE).collect();
@@ -228,7 +172,6 @@ pub(crate) async fn bulk_upsert_documents(
total_chunks = chunks.len(),
chunk_size = CHUNK_SIZE,
index = %index,
- shape = if join_shape { "join" } else { "flat" },
"starting chunked bulk upsert"
);
@@ -239,11 +182,7 @@ pub(crate) async fn bulk_upsert_documents(
"processing chunk"
);
- let chunk_result = if join_shape {
- bulk_upsert_single_chunk_join(client, chunk, index).await
- } else {
- bulk_upsert_single_chunk_flat(client, chunk, index).await
- };
+ let chunk_result = bulk_upsert_single_chunk(client, chunk, index).await;
match chunk_result {
Ok(r) => {
@@ -278,6 +217,10 @@ pub(crate) async fn bulk_upsert_documents(
Ok(overall_result)
}
+/// Upsert a single chunk: parent index followed by child index. Uses a
+/// 2-op bulk so both land in one request. Full-overwrite `index`
+/// semantics on the parent ensure omitted optional fields (e.g.
+/// `sub_type`) get cleared on Some→None transitions.
#[tracing::instrument(skip(client))]
pub(crate) async fn upsert_document(
client: &opensearch::OpenSearch,
@@ -285,64 +228,6 @@ pub(crate) async fn upsert_document(
index_override: Option<&str>,
) -> Result<()> {
let index = resolve_destination(index_override);
- if destination_uses_join_shape(index) {
- return upsert_document_join(client, args, index).await;
- }
- upsert_document_flat(client, args, index).await
-}
-
-async fn upsert_document_flat(
- client: &opensearch::OpenSearch,
- args: &UpsertDocumentArgs,
- index: &str,
-) -> Result<()> {
- let id = format!("{}:{}", args.document_id, args.node_id);
- let response = client
- .index(opensearch::IndexParts::IndexId(index, &id))
- .body(args)
- .send()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_document_flat".to_string()),
- })?;
-
- let status_code = response.status_code();
- if status_code.is_success() {
- tracing::trace!(id=%id, "document upserted successfully");
- return Ok(());
- }
-
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_document_flat".to_string()),
- })?;
-
- tracing::error!(
- status_code = ?status_code,
- body = ?body,
- "error upserting document",
- );
-
- Err(OpensearchClientError::Unknown {
- details: body,
- method: Some("upsert_document_flat".to_string()),
- })
-}
-
-/// Upsert a single chunk in the join shape: parent index followed by
-/// child index. Uses a 2-op bulk so both land in one request. Full-
-/// overwrite `index` semantics on the parent ensure omitted optional
-/// fields (e.g. `sub_type`) get cleared on Some→None transitions.
-async fn upsert_document_join(
- client: &opensearch::OpenSearch,
- args: &UpsertDocumentArgs,
- index: &str,
-) -> Result<()> {
let parent_id = args.document_id.as_str();
let routing = parent_id;
@@ -368,123 +253,31 @@ async fn upsert_document_join(
child_doc_body(args).to_string(),
];
- let result =
- super::bulk_upsert_to_index(client, index, bulk_body, "upsert_document_join").await?;
+ let result = super::bulk_upsert_to_index(client, index, bulk_body, "upsert_document").await?;
if result.failed > 0 {
return Err(OpensearchClientError::Unknown {
details: format!(
- "upsert_document_join had {} failures: {:?}",
+ "upsert_document had {} failures: {:?}",
result.failed, result.errors
),
- method: Some("upsert_document_join".to_string()),
+ method: Some("upsert_document".to_string()),
});
}
- tracing::trace!(id=%child_id, parent=%parent_id, "document upserted successfully (join)");
+ tracing::trace!(id=%child_id, parent=%parent_id, "document upserted successfully");
Ok(())
}
/// Update the denormalized `document_name` for an existing document.
///
-/// Flat shape: `update_by_query` fans the new name across every chunk
-/// doc. Join shape: a single partial-update on the parent (children
-/// don't carry `document_name`).
+/// A single partial-update on the parent doc; children don't carry
+/// `document_name`. Routing must match the parent's routing (= parent
+/// _id = document_id).
pub(crate) async fn update_document_metadata(
client: &opensearch::OpenSearch,
document_id: &str,
document_name: &str,
-) -> Result<()> {
- if alias_uses_join_shape() {
- update_document_metadata_join(client, document_id, document_name).await
- } else {
- update_document_metadata_flat(client, document_id, document_name).await
- }
-}
-
-async fn update_document_metadata_flat(
- client: &opensearch::OpenSearch,
- document_id: &str,
- document_name: &str,
-) -> Result<()> {
- use opensearch::UpdateByQueryParts;
- use serde_json::json;
-
- let query = json!({
- "query": {
- "term": {
- "entity_id": document_id
- }
- },
- "script": {
- "source": "ctx._source.document_name = params.document_name",
- "params": {
- "document_name": document_name
- }
- }
- });
-
- let response = client
- .update_by_query(UpdateByQueryParts::Index(
- &[SearchIndex::Documents.as_ref()],
- ))
- .body(query)
- .send()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("update_document_metadata_flat".to_string()),
- })?;
-
- let status_code = response.status_code();
- if status_code.is_success() {
- let response_body: serde_json::Value =
- response
- .json()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("update_document_metadata_flat".to_string()),
- })?;
-
- let updated_count = response_body["updated"].as_u64().unwrap_or(0);
- tracing::info!(
- document_id=%document_id,
- document_name=%document_name,
- updated_count=%updated_count,
- "document metadata updated successfully (flat)"
- );
- return Ok(());
- }
-
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("update_document_metadata_flat".to_string()),
- })?;
-
- tracing::error!(
- status_code=?status_code,
- body=?body,
- document_id=%document_id,
- "error updating document metadata (flat)",
- );
-
- Err(OpensearchClientError::Unknown {
- details: body,
- method: Some("update_document_metadata_flat".to_string()),
- })
-}
-
-/// Partial update on the parent doc. Routing must match the parent's
-/// routing (= parent _id = document_id).
-async fn update_document_metadata_join(
- client: &opensearch::OpenSearch,
- document_id: &str,
- document_name: &str,
) -> Result<()> {
use serde_json::json;
@@ -505,7 +298,7 @@ async fn update_document_metadata_join(
.await
.map_err(|err| OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("update_document_metadata_join".to_string()),
+ method: Some("update_document_metadata".to_string()),
})?;
let status_code = response.status_code();
@@ -513,7 +306,7 @@ async fn update_document_metadata_join(
tracing::info!(
document_id=%document_id,
document_name=%document_name,
- "document metadata updated successfully (join)"
+ "document metadata updated successfully"
);
return Ok(());
}
@@ -524,19 +317,19 @@ async fn update_document_metadata_join(
.await
.map_err(|err| OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("update_document_metadata_join".to_string()),
+ method: Some("update_document_metadata".to_string()),
})?;
tracing::error!(
status_code=?status_code,
body=?body,
document_id=%document_id,
- "error updating document metadata (join)",
+ "error updating document metadata",
);
Err(OpensearchClientError::Unknown {
details: body,
- method: Some("update_document_metadata_join".to_string()),
+ method: Some("update_document_metadata".to_string()),
})
}
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
index 04982ed23b..39154a9805 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
@@ -63,14 +63,6 @@ fn child_doc_body_omits_raw_content_when_none() {
assert!(doc.get("raw_content").is_none());
}
-#[test]
-fn destination_uses_join_shape_for_v2() {
- use crate::documents_shape::{DOCUMENTS_V2, destination_uses_join_shape};
- assert!(destination_uses_join_shape(DOCUMENTS_V2));
- assert!(!destination_uses_join_shape("documents_v1"));
- assert!(!destination_uses_join_shape("documents_join_test"));
-}
-
#[test]
fn resolve_destination_defaults_to_documents_alias() {
assert_eq!(resolve_destination(None), SearchIndex::Documents.as_ref());
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
index aad511dba5..89b75fcefe 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
@@ -197,33 +197,17 @@ pub(in crate::api::search) async fn perform_unified_search(
// Set terms on each index's search args.
//
- // Emails and channels both get whitespace-split terms — emails match
- // each term independently across many fields ANDed inside OpenSearch;
+ // Every content index gets whitespace-split terms. Emails match each
+ // term independently across many fields ANDed inside OpenSearch;
// channel messages are single-doc-per-message so each token must
- // appear in the same message via bool.must. Documents and chats get
- // split terms once their alias points at a join-shape index, where
- // each term becomes a separate has_child clause ANDed via bool.must.
- let document_terms = if opensearch_client::documents_shape::alias_uses_join_shape() {
- split_search_terms(&terms)
- } else {
- terms.clone()
- };
- let chat_terms = if opensearch_client::chats_shape::alias_uses_join_shape() {
- split_search_terms(&terms)
- } else {
- terms.clone()
- };
- let call_record_terms = if opensearch_client::call_records_shape::alias_uses_join_shape() {
- split_search_terms(&terms)
- } else {
- terms.clone()
- };
- let channel_terms = split_search_terms(&terms);
- filter_document_response.terms = document_terms;
- filter_channel_response.terms = channel_terms;
- filter_chat_response.terms = chat_terms;
+ // appear in the same message via bool.must. Documents, chats, and
+ // call records are join-shape, where each term becomes a separate
+ // has_child clause ANDed via bool.must.
+ filter_document_response.terms = split_search_terms(&terms);
+ filter_channel_response.terms = split_search_terms(&terms);
+ filter_chat_response.terms = split_search_terms(&terms);
filter_email_response.terms = email_terms.clone();
- filter_call_record_response.terms = call_record_terms;
+ filter_call_record_response.terms = split_search_terms(&terms);
// Clone terms for use in name searches
let name_search_term = terms[0].clone();