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.

feat(search): move document name search into OpenSearch (#4244)

gbirmanc2ac3cb49f62
diff --git a/rust/cloud-storage/models_search_cursor/src/lib.rs b/rust/cloud-storage/models_search_cursor/src/lib.rs
index b4226d1c01..cc544415e4 100644
--- a/rust/cloud-storage/models_search_cursor/src/lib.rs
+++ b/rust/cloud-storage/models_search_cursor/src/lib.rs
@@ -152,8 +152,6 @@ impl SearchCursorOption {
/// The search cursor contains all the individual `SearchCursorOption` for each search method.
#[derive(Debug, serde::Serialize, serde::Deserialize, Default)]
pub struct SearchCursor {
- /// The document name cursor
- pub document_name_cursor: SearchCursorOption,
/// The chat name cursor
pub chat_name_cursor: SearchCursorOption,
/// The content cursor
@@ -184,8 +182,7 @@ impl SearchCursor {
/// Returns if the cursor is fully exhausted
pub fn is_exhausted(&self) -> bool {
- self.document_name_cursor.is_done()
- && self.chat_name_cursor.is_done()
+ self.chat_name_cursor.is_done()
&& self.content_cursor.is_done()
&& self.project_name_cursor.is_done()
&& self.crm_company_cursor.is_done()
@@ -228,7 +225,6 @@ mod test {
#[test]
fn is_exhausted_requires_crm_done() {
let mut cursor = SearchCursor {
- document_name_cursor: SearchCursorOption::Done,
chat_name_cursor: SearchCursorOption::Done,
content_cursor: SearchCursorOption::Done,
project_name_cursor: SearchCursorOption::Done,
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rs
index d9e30373e4..e8109447d1 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs
@@ -38,18 +38,34 @@ const INNER_HITS_PER_TERM: u32 = 100;
/// query cost bounded without truncating common cases.
const MATCH_PHRASE_PREFIX_MAX_EXPANSIONS: u32 = 256;
+/// Which fields a document search matches against.
+///
+/// `Content` (the default) preserves the chunk-only `has_child` behavior.
+/// `Name` matches the parent `document_name`. `NameContent` matches either.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum DocumentSearchMode {
+ /// Match terms against the parent `document_name` only.
+ Name,
+ /// Match terms against child chunk `content` only.
+ #[default]
+ Content,
+ /// Match a document by its name or its content.
+ NameContent,
+}
+
#[derive(Clone)]
pub(crate) struct DocumentSearchConfig;
impl SearchQueryConfig for DocumentSearchConfig {
const USER_ID_KEY: Option<&'static str> = Some("owner_id");
- const TITLE_KEY: &'static str = "name";
+ const TITLE_KEY: &'static str = "document_name";
const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::Documents;
}
pub(crate) struct DocumentQueryBuilder {
inner: SearchQueryBuilder<DocumentSearchConfig>,
sub_types: Vec<String>,
+ mode: DocumentSearchMode,
}
impl DocumentQueryBuilder {
@@ -57,9 +73,15 @@ impl DocumentQueryBuilder {
Self {
inner: SearchQueryBuilder::new(terms),
sub_types: Vec::new(),
+ mode: DocumentSearchMode::default(),
}
}
+ pub fn mode(mut self, mode: DocumentSearchMode) -> Self {
+ self.mode = mode;
+ self
+ }
+
// Copy function signature from SearchQueryBuilder
delegate_methods! {
fn match_type(match_type: &str) -> Self;
@@ -110,31 +132,67 @@ impl DocumentQueryBuilder {
bool_query.filter(QueryType::terms("sub_type", self.sub_types.clone()));
}
- // One has_child clause per term, ANDed via bool.must. Each carries
- // its own inner_hits so highlights and chunk-nav data come back
- // alongside the parent. `size` is bumped well above the OpenSearch
- // default of 3 so a doc with many matching chunks returns all of
- // them (the flat shape had no per-doc cap; this preserves parity).
- //
- // The inner_hits highlight uses a shared `highlight_query` that
- // ORs every search term, so a chunk returned by any one
- // has_child clause gets tags around *every* term it contains —
- // not just the term whose clause produced it.
- let highlight_query =
- build_all_terms_highlight_query(&self.inner.terms, &self.inner.match_type);
- for (idx, term) in self.inner.terms.iter().enumerate() {
- let inner_query = build_child_content_query(term, &self.inner.match_type);
- let inner_hits = InnerHits::new()
- .name(format!("term_{idx}"))
- .size(INNER_HITS_PER_TERM)
- .highlight(inner_hits_content_highlight(&highlight_query));
- let has_child = HasChildQuery::new(CHILD_RELATION, inner_query).inner_hits(inner_hits);
- bool_query.must(has_child.into());
+ // Match clause(s) per mode: the parent `document_name` (Name), child
+ // chunk `content` via has_child (Content), or either (NameContent).
+ let include_name = matches!(
+ self.mode,
+ DocumentSearchMode::Name | DocumentSearchMode::NameContent
+ );
+ let include_content = matches!(
+ self.mode,
+ DocumentSearchMode::Content | DocumentSearchMode::NameContent
+ );
+
+ if include_name && include_content {
+ // A document matches when its name matches every term, or every
+ // term matches some chunk's content.
+ let mut content_bool = BoolQueryBuilder::new();
+ for clause in self.build_content_has_child_clauses() {
+ content_bool.must(clause);
+ }
+ let mut matched = BoolQueryBuilder::new();
+ matched.minimum_should_match(1);
+ matched.should(content_bool.build().into());
+ matched.should(self.inner.build_title_term_query()?);
+ bool_query.must(matched.build().into());
+ } else if include_name {
+ bool_query.must(self.inner.build_title_term_query()?);
+ } else {
+ // Content-only: one has_child clause per term, ANDed via bool.must.
+ for clause in self.build_content_has_child_clauses() {
+ bool_query.must(clause);
+ }
}
Ok(bool_query)
}
+ /// One `has_child` clause per term, each carrying its own `inner_hits` so
+ /// highlights and chunk-nav data come back alongside the parent. `size` is
+ /// bumped well above OpenSearch's default of 3 so a doc with many matching
+ /// chunks returns all of them. The shared `highlight_query` ORs every term
+ /// so a returned chunk gets tagged for every term it contains, not just the
+ /// one its clause matched.
+ fn build_content_has_child_clauses<'a>(&'a self) -> Vec<QueryType<'a>> {
+ let highlight_query =
+ build_all_terms_highlight_query(&self.inner.terms, &self.inner.match_type);
+ self.inner
+ .terms
+ .iter()
+ .enumerate()
+ .map(|(idx, term)| {
+ let inner_query = build_child_content_query(term, &self.inner.match_type);
+ let inner_hits = InnerHits::new()
+ .name(format!("term_{idx}"))
+ .size(INNER_HITS_PER_TERM)
+ .highlight(inner_hits_content_highlight(&highlight_query));
+ HasChildQuery::new(CHILD_RELATION, inner_query)
+ .inner_hits(inner_hits)
+ .into()
+ })
+ .collect()
+ }
+
/// Build the access-control filter using parent-side fields: either
/// `entity_id ∈ ids` (ids_only), `owner_id` alone, or a should-bool of
/// both when ids are provided alongside the owner.
@@ -243,6 +301,7 @@ pub struct DocumentSearchArgs {
pub collapse: bool,
pub ids_only: bool,
pub sub_types: Vec<String>,
+ pub mode: DocumentSearchMode,
}
impl From<DocumentSearchArgs> for DocumentQueryBuilder {
@@ -256,6 +315,7 @@ impl From<DocumentSearchArgs> for DocumentQueryBuilder {
.collapse(args.collapse)
.ids_only(args.ids_only)
.sub_types(args.sub_types)
+ .mode(args.mode)
}
}
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 68e65fe0f2..67312c4fed 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs
@@ -154,6 +154,74 @@ fn test_build_bool_query_join_shape_has_inner_hits() -> anyhow::Result<()> {
Ok(())
}
+#[test]
+fn test_build_bool_query_name_mode_matches_document_name() -> anyhow::Result<()> {
+ let builder = DocumentQueryBuilder::new(vec!["report".to_string()])
+ .match_type("partial")
+ .user_id("alice")
+ .mode(DocumentSearchMode::Name);
+
+ let json = builder.build_bool_query()?.build().to_json();
+
+ // Access + index filters are unchanged in name mode.
+ let filter = json["bool"]["filter"].as_array().expect("filter array");
+ assert!(filter.contains(&serde_json::json!({"term": {"_index": "documents"}})));
+ assert!(filter.contains(&serde_json::json!({"term": {"owner_id": "alice"}})));
+
+ // The match clause targets the parent document_name, not child content.
+ let must = json["bool"]["must"].as_array().expect("must array");
+ assert_eq!(must.len(), 1, "name mode emits one title clause: {must:?}");
+ assert_eq!(
+ must[0]["match_phrase_prefix"]["document_name"]["query"],
+ "report"
+ );
+ assert!(
+ !json.to_string().contains("has_child"),
+ "name mode must not query child content: {json}"
+ );
+ Ok(())
+}
+
+#[test]
+fn test_build_bool_query_name_content_mode_matches_either() -> anyhow::Result<()> {
+ let builder = DocumentQueryBuilder::new(vec!["report".to_string()])
+ .match_type("partial")
+ .user_id("alice")
+ .mode(DocumentSearchMode::NameContent);
+
+ let json = builder.build_bool_query()?.build().to_json();
+
+ let must = json["bool"]["must"].as_array().expect("must array");
+ assert_eq!(
+ must.len(),
+ 1,
+ "name_content wraps matching in one should-bool: {must:?}"
+ );
+ assert_eq!(must[0]["bool"]["minimum_should_match"], 1);
+ let should = must[0]["bool"]["should"].as_array().expect("should array");
+ assert_eq!(
+ should.len(),
+ 2,
+ "expected a name branch and a content branch: {should:?}"
+ );
+
+ // One branch matches the parent document_name…
+ assert!(
+ should
+ .iter()
+ .any(|c| c["match_phrase_prefix"]["document_name"]["query"] == "report"),
+ "missing document_name branch: {should:?}"
+ );
+ // …the other matches child content via has_child.
+ assert!(
+ should
+ .iter()
+ .any(|c| c["bool"]["must"][0]["has_child"]["type"] == "chunk"),
+ "missing has_child content branch: {should:?}"
+ );
+ Ok(())
+}
+
#[test]
fn document_index_deserializes_parent_shape() {
// Parent docs carry only parent-level metadata in `_source`; the
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index bf1513f081..ea867f3d28 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -15,12 +15,13 @@ use crate::{
chats::{ChatIndex, ChatQueryBuilder, ChatSearchArgs, ChatSearchConfig},
documents::{
DocumentIndex, DocumentQueryBuilder, DocumentSearchArgs, DocumentSearchConfig,
+ DocumentSearchMode,
},
emails::{EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig},
model::{
DefaultSearchResponse, Hit, MacroEm, SearchGotoCallRecord, SearchGotoChannel,
- SearchGotoChat, SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit,
- exclude_source_content, inject_fragment_size, parse_highlight_hit,
+ SearchGotoContent, SearchGotoEmail, SearchHit, exclude_source_content,
+ inject_fragment_size, parse_highlight_hit,
},
query::Keys,
},
@@ -77,6 +78,7 @@ impl From<UnifiedSearchArgs> for DocumentSearchArgs {
ids_only: args.document_search_args.ids_only,
document_ids: args.document_search_args.document_ids,
sub_types: args.document_search_args.sub_types,
+ mode: args.document_search_args.mode,
}
}
}
@@ -171,6 +173,7 @@ pub struct UnifiedDocumentSearchArgs {
pub document_ids: Vec<String>,
pub ids_only: bool,
pub sub_types: Vec<String>,
+ pub mode: DocumentSearchMode,
}
#[derive(Debug, Default, Clone)]
@@ -307,20 +310,48 @@ where
fn expand_hit_into_search_hits(hit: Hit<UnifiedSearchIndex>) -> Vec<SearchHit> {
match &hit.source {
UnifiedSearchIndex::Document(parent) => {
- let Some(inner) = hit.inner_hits.as_ref() else {
- return vec![hit.into()];
- };
let entity_id = parent.entity_id;
let updated_at = parent
.updated_at_seconds
.and_then(|s| DateTime::from_timestamp(s, 0));
- let expanded = crate::search::documents::expand_inner_hits_to_search_hits(
- entity_id, updated_at, inner,
- );
- if expanded.is_empty() {
+
+ let mut out: Vec<SearchHit> = Vec::new();
+
+ // A name match surfaces as a parent-level hit. The content branch
+ // lives in inner_hits and never highlights `document_name`, so a
+ // top-level highlight on that field means the name matched. `goto`
+ // is None (no chunk to navigate to) so downstream grouping treats
+ // it as a name match, not an empty content result.
+ if let Some(highlight) = hit.highlight.as_ref()
+ && highlight.contains_key(DocumentSearchConfig::TITLE_KEY)
+ {
+ out.push(SearchHit {
+ entity_id,
+ entity_type: SearchEntityType::Documents,
+ score: hit.score,
+ highlight: parse_highlight_hit(
+ highlight.clone(),
+ Keys {
+ title_key: DocumentSearchConfig::TITLE_KEY,
+ content_key: DocumentSearchConfig::CONTENT_KEY,
+ },
+ ),
+ goto: None,
+ updated_at,
+ });
+ }
+
+ // Content matches surface as one hit per matching chunk.
+ if let Some(inner) = hit.inner_hits.as_ref() {
+ out.extend(crate::search::documents::expand_inner_hits_to_search_hits(
+ entity_id, updated_at, inner,
+ ));
+ }
+
+ if out.is_empty() {
return vec![hit.into()];
}
- expanded
+ out
}
UnifiedSearchIndex::Chat(parent) => {
let Some(inner) = hit.inner_hits.as_ref() else {
@@ -399,14 +430,7 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
)
})
.unwrap_or_default(),
- goto: Some(SearchGotoContent::Documents(SearchGotoDocument {
- // 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,
- })),
+ goto: None,
updated_at: a
.updated_at_seconds
.and_then(|s| DateTime::from_timestamp(s, 0)),
@@ -461,14 +485,7 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
)
})
.unwrap_or_default(),
- goto: Some(SearchGotoContent::Chats(SearchGotoChat {
- // 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(),
- })),
+ goto: None,
updated_at: a
.updated_at_seconds
.and_then(|s| DateTime::from_timestamp(s, 0)),
@@ -604,6 +621,7 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
let highlight = Highlight::new()
.require_field_match(true)
.field("content", em_field().number_of_fragments(1))
+ .field("document_name", em_field().number_of_fragments(0))
.field("subject", em_field().number_of_fragments(0))
.field("sender", em_field().number_of_fragments(0))
.field("sender_name", em_field().number_of_fragments(0))
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 ec1217da33..fe33d88eee 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -5,6 +5,45 @@ use chrono::Utc;
use models_search_cursor::SearchMethodCursor;
use opensearch_query_builder::ToOpenSearchJson;
+#[test]
+fn expand_document_name_highlight_yields_name_hit_without_goto() {
+ use std::collections::HashMap;
+ use uuid::Uuid;
+
+ let entity_id = "00000000-0000-0000-0000-000000000001"
+ .parse::<Uuid>()
+ .unwrap();
+ // A parent document whose name matched: a top-level `document_name`
+ // highlight, no inner_hits (the content branch did not match).
+ let hit = Hit {
+ score: Some(2.0),
+ source: UnifiedSearchIndex::Document(DocumentIndex {
+ entity_id,
+ document_name: "Q3 Report".to_string(),
+ owner_id: "alice".to_string(),
+ file_type: "md".to_string(),
+ updated_at_seconds: Some(1_779_000_000),
+ }),
+ highlight: Some(HashMap::from([(
+ "document_name".to_string(),
+ vec!["Q3 <macro_em>Rep</macro_em>ort".to_string()],
+ )])),
+ inner_hits: None,
+ };
+
+ let results = expand_hit_into_search_hits(hit);
+ assert_eq!(results.len(), 1, "name-only match yields a single hit");
+ assert_eq!(results[0].entity_id, entity_id);
+ assert!(
+ results[0].goto.is_none(),
+ "a name match carries no chunk goto so grouping treats it as a name result"
+ );
+ assert_eq!(
+ results[0].highlight.name.as_deref(),
+ Some("Q3 <macro_em>Rep</macro_em>ort")
+ );
+}
+
#[test]
fn test_deserialization() -> anyhow::Result<()> {
let json = serde_json::json!({
@@ -482,6 +521,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
"highlight": {
"fields": {
"content": { "number_of_fragments": 1, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "document_name": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
"subject": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
"sender": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
"sender_name": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
@@ -799,6 +839,7 @@ fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
"highlight": {
"fields": {
"content": { "number_of_fragments": 1, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "document_name": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
"subject": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
"sender": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
"sender_name": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs
index 2088cc3272..f8746bae7b 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs
@@ -1,9 +1,6 @@
use crate::api::search::simple::SearchError;
use item_filters::DocumentFilters;
-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use model::item::{ShareableItem, ShareableItemType, UserAccessibleItem};
-use opensearch_client::search::model::{Highlight, SearchHit};
-use sqlx::{Pool, Postgres, types::Uuid};
use crate::api::context::SearchHandlerState;
@@ -124,58 +121,3 @@ pub(in crate::api::search) async fn filter_documents(
ids_only,
})
}
-
-/// Performs the name search over document names
-#[tracing::instrument(skip(db), err)]
-pub(in crate::api::search::simple) async fn search_names<'a>(
- db: &Pool<Postgres>,
- user_id: &MacroUserId<Lowercase<'a>>,
- filter_document_response: &FilterDocumentResponse,
- term: String,
- limit: u32,
- cursor: models_search_cursor::SearchCursorOption,
-) -> Result<(Vec<SearchHit>, models_search_cursor::SearchCursorOption), SearchError> {
- // If cursor is Done, no more results to fetch
- let inner_cursor = match cursor {
- models_search_cursor::SearchCursorOption::Done => {
- return Ok((vec![], models_search_cursor::SearchCursorOption::Done));
- }
- models_search_cursor::SearchCursorOption::NotDone(c) => c,
- };
-
- let document_uuids = filter_document_response
- .document_ids
- .iter()
- .map(|d| d.parse().unwrap())
- .collect::<Vec<Uuid>>();
-
- name_search::search_document_names(
- db,
- user_id,
- &document_uuids,
- term,
- filter_document_response.ids_only,
- limit,
- inner_cursor,
- )
- .await
- .map_err(SearchError::NameSearch)
- .map(|response| {
- let hits = response
- .items
- .into_iter()
- .map(|n| SearchHit {
- entity_id: n.entity_id,
- entity_type: n.entity_type,
- score: None,
- highlight: Highlight {
- name: Some(n.name),
- ..Default::default()
- },
- goto: None,
- updated_at: Some(n.updated_at),
- })
- .collect();
- (hits, response.cursor)
- })
-}
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 d3c3ce7499..54839674fb 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
@@ -1,7 +1,7 @@
use crate::api::search::simple::filter::FilterVariantToSearchArgs;
use crate::api::search::crm_company;
-use crate::api::search::simple::{simple_chat, simple_document, simple_project};
+use crate::api::search::simple::{simple_chat, simple_project};
use crate::api::{
context::SearchHandlerState,
search::{SearchPaginationParams, simple::SearchError},
@@ -21,13 +21,13 @@ use models_search::{
unified::{SimpleUnifiedSearchResponse, UnifiedSearchRequest},
};
use models_search_cursor::{SearchCursor, SearchCursorOption, SearchMethodCursor};
+use opensearch_client::search::documents::DocumentSearchMode;
use opensearch_client::search::model::SearchHit;
use opensearch_client::search::unified::UnifiedSearchArgs;
/// Identifies the source of a search result for cursor regeneration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SearchSource {
- DocumentName,
ChatName,
ProjectName,
Content,
@@ -268,10 +268,6 @@ pub(in crate::api::search) async fn perform_unified_search(
// Extract individual cursors from the combined cursor (SearchCursorOption)
// Clone for use in async blocks and for cursor regeneration
- let document_cursor = cursor
- .as_ref()
- .map(|c| c.document_name_cursor.clone())
- .unwrap_or_default();
let chat_cursor = cursor
.as_ref()
.map(|c| c.chat_name_cursor.clone())
@@ -292,7 +288,6 @@ pub(in crate::api::search) async fn perform_unified_search(
.unwrap_or_default();
// Clone cursors for passing to search functions (originals needed for cursor regeneration)
- let document_cursor_for_search = document_cursor.clone();
let chat_cursor_for_search = chat_cursor.clone();
let project_cursor_for_search = project_cursor.clone();
let content_cursor_for_search = content_cursor.clone();
@@ -338,30 +333,7 @@ pub(in crate::api::search) async fn perform_unified_search(
// Call search functions in parallel for included entity types
// search_names handles Done cursors internally by returning early
- let (doc_name_results, chat_results, project_results, content_results, crm_results) = tokio::join!(
- async {
- if should_include_documents {
- match search_on {
- SearchOn::Name | SearchOn::NameContent => {
- simple_document::search_names(
- &ctx.db,
- &user_id,
- &simple_document::FilterDocumentResponse {
- ids_only: filter_document_response.ids_only,
- document_ids: filter_document_response.document_ids,
- },
- name_search_term.clone(),
- page_size,
- document_cursor_for_search,
- )
- .await
- }
- SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),
- }
- } else {
- Ok((vec![], SearchCursorOption::Done))
- }
- },
+ let (chat_results, project_results, content_results, crm_results) = tokio::join!(
async {
if should_include_chats {
match search_on {
@@ -409,13 +381,27 @@ pub(in crate::api::search) async fn perform_unified_search(
}
},
async {
- // For Name-only mode, only search emails via OpenSearch (subject field
- // via simple_query_string). Other entity types use PG name searches above.
+ // Documents and email subjects are name-searched in OpenSearch.
+ // In Name mode keep only those two indices: chats and projects
+ // still name-search in Postgres above, and channels/call records
+ // have no name concept. Documents match `document_name`, emails
+ // their subject.
let mut args = unified_search_args;
- if matches!(search_on, SearchOn::Name) {
- args.search_indices
- .retain(|i| *i == models_opensearch::OpenSearchEntityType::Emails);
- args.email_search_args.subject_only = true;
+ match search_on {
+ SearchOn::Name => {
+ args.document_search_args.mode = DocumentSearchMode::Name;
+ args.email_search_args.subject_only = true;
+ args.search_indices.retain(|i| {
+ *i == models_opensearch::OpenSearchEntityType::Documents
+ || *i == models_opensearch::OpenSearchEntityType::Emails
+ });
+ }
+ SearchOn::NameContent => {
+ args.document_search_args.mode = DocumentSearchMode::NameContent;
+ }
+ SearchOn::Content => {
+ args.document_search_args.mode = DocumentSearchMode::Content;
+ }
}
if args.search_indices.is_empty() {
Ok((vec![], SearchCursorOption::Done))
@@ -446,14 +432,12 @@ pub(in crate::api::search) async fn perform_unified_search(
);
// Extract results and next cursors
- let (doc_hits, doc_next_cursor) = doc_name_results?;
let (chat_hits, chat_next_cursor) = chat_results?;
let (project_hits, project_next_cursor) = project_results?;
let (content_hits, content_next_cursor) = content_results?;
let (crm_hits, crm_next_cursor) = crm_results?;
// Track original counts before combining
- let doc_name_count = doc_hits.len();
let chat_name_count = chat_hits.len();
let project_name_count = project_hits.len();
let content_count = content_hits.len();
@@ -462,7 +446,6 @@ pub(in crate::api::search) async fn perform_unified_search(
let final_tagged = {
let _span = tracing::info_span!(
"combine_and_sort_results",
- doc_name_count,
chat_name_count,
project_name_count,
content_count
@@ -471,10 +454,6 @@ pub(in crate::api::search) async fn perform_unified_search(
// Wrap results with source tags
let mut combined: Vec<TaggedSearchHit> = Vec::new();
- combined.extend(doc_hits.into_iter().map(|hit| TaggedSearchHit {
- hit,
- source: SearchSource::DocumentName,
- }));
combined.extend(chat_hits.into_iter().map(|hit| TaggedSearchHit {
hit,
source: SearchSource::ChatName,
@@ -521,10 +500,6 @@ pub(in crate::api::search) async fn perform_unified_search(
let _span = tracing::info_span!("compute_pagination_cursors").entered();
// Count included results by source
- let included_doc_names = final_tagged
- .iter()
- .filter(|h| h.source == SearchSource::DocumentName)
- .count();
let included_chat_names = final_tagged
.iter()
.filter(|h| h.source == SearchSource::ChatName)
@@ -543,14 +518,6 @@ pub(in crate::api::search) async fn perform_unified_search(
.count();
// Generate new cursors using helper function
- let new_doc_cursor = compute_next_cursor(
- &doc_next_cursor,
- included_doc_names,
- doc_name_count,
- find_last_of_source(&final_tagged, SearchSource::DocumentName),
- &document_cursor,
- );
-
let new_chat_cursor = compute_next_cursor(
&chat_next_cursor,
included_chat_names,
@@ -584,15 +551,13 @@ pub(in crate::api::search) async fn perform_unified_search(
);
// Build next cursor if any source has more results
- let has_more = new_doc_cursor.has_more()
- || new_chat_cursor.has_more()
+ let has_more = new_chat_cursor.has_more()
|| new_project_cursor.has_more()
|| new_content_cursor.has_more()
|| new_crm_cursor.has_more();
if has_more {
let cursor = SearchCursor {
- document_name_cursor: new_doc_cursor,
chat_name_cursor: new_chat_cursor,
content_cursor: new_content_cursor,
project_name_cursor: new_project_cursor,
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
index 3489c63500..666d29eae6 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
@@ -40,7 +40,7 @@ fn test_compute_next_cursor_search_is_done_returns_done() {
Some(&make_tagged_hit(
Uuid::new_v4(),
Some(ts(1000)),
- SearchSource::DocumentName,
+ SearchSource::ProjectName,
)),
&SearchCursorOption::NotDone(None),
);
@@ -54,7 +54,7 @@ fn test_compute_next_cursor_excluded_results_with_included_generates_cursor() {
// generate cursor from the last included hit
let entity_id = Uuid::new_v4();
let timestamp = ts(1000);
- let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::DocumentName);
+ let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::ProjectName);
let result = compute_next_cursor(
&SearchCursorOption::NotDone(None), // search says not done
@@ -207,12 +207,12 @@ fn test_find_last_of_source_finds_correct_source() {
let doc2_id = Uuid::new_v4();
let results = vec![
- make_tagged_hit(doc_id, Some(ts(1000)), SearchSource::DocumentName),
+ make_tagged_hit(doc_id, Some(ts(1000)), SearchSource::ProjectName),
make_tagged_hit(chat_id, Some(ts(2000)), SearchSource::ChatName),
- make_tagged_hit(doc2_id, Some(ts(3000)), SearchSource::DocumentName),
+ make_tagged_hit(doc2_id, Some(ts(3000)), SearchSource::ProjectName),
];
- let last_doc = find_last_of_source(&results, SearchSource::DocumentName);
+ let last_doc = find_last_of_source(&results, SearchSource::ProjectName);
assert!(last_doc.is_some());
assert_eq!(last_doc.unwrap().hit.entity_id, doc2_id);
@@ -224,7 +224,7 @@ fn test_find_last_of_source_finds_correct_source() {
#[test]
fn test_find_last_of_source_returns_none_when_not_found() {
let results = vec![
- make_tagged_hit(Uuid::new_v4(), Some(ts(1000)), SearchSource::DocumentName),
+ make_tagged_hit(Uuid::new_v4(), Some(ts(1000)), SearchSource::ProjectName),
make_tagged_hit(Uuid::new_v4(), Some(ts(2000)), SearchSource::ChatName),
];
@@ -235,7 +235,7 @@ fn test_find_last_of_source_returns_none_when_not_found() {
#[test]
fn test_find_last_of_source_empty_results() {
let results: Vec<TaggedSearchHit> = vec![];
- let result = find_last_of_source(&results, SearchSource::DocumentName);
+ let result = find_last_of_source(&results, SearchSource::ProjectName);
assert!(result.is_none());
}
@@ -245,7 +245,7 @@ fn test_find_last_of_source_empty_results() {
fn test_cursor_from_tagged_with_timestamp() {
let entity_id = Uuid::new_v4();
let timestamp = ts(1000);
- let hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::DocumentName);
+ let hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::ProjectName);
let cursor = cursor_from_tagged(&hit);
assert!(cursor.is_some());
@@ -271,51 +271,63 @@ fn test_cursor_from_tagged_without_timestamp() {
#[test]
fn test_cursor_logic_pagination_scenario() {
// Simulate a pagination scenario where:
- // - Search returned 10 documents
+ // - Search returned 10 projects
// - Only 3 made it into the final page (others had newer timestamps from other sources)
- // - The cursor should point to the last included document
+ // - The cursor should point to the last included project
- let doc_ids: Vec<Uuid> = (0..10).map(|_| Uuid::new_v4()).collect();
+ let project_ids: Vec<Uuid> = (0..10).map(|_| Uuid::new_v4()).collect();
let timestamps: Vec<chrono::DateTime<Utc>> = (0..10).map(|i| ts(1000 + i * 100)).collect();
// Create the final tagged results (simulating merged & sorted output)
let final_tagged: Vec<TaggedSearchHit> = vec![
make_tagged_hit(Uuid::new_v4(), Some(ts(5000)), SearchSource::ChatName),
- make_tagged_hit(doc_ids[9], Some(timestamps[9]), SearchSource::DocumentName),
+ make_tagged_hit(
+ project_ids[9],
+ Some(timestamps[9]),
+ SearchSource::ProjectName,
+ ),
make_tagged_hit(Uuid::new_v4(), Some(ts(4000)), SearchSource::Content),
- make_tagged_hit(doc_ids[8], Some(timestamps[8]), SearchSource::DocumentName),
- make_tagged_hit(doc_ids[7], Some(timestamps[7]), SearchSource::DocumentName),
+ make_tagged_hit(
+ project_ids[8],
+ Some(timestamps[8]),
+ SearchSource::ProjectName,
+ ),
+ make_tagged_hit(
+ project_ids[7],
+ Some(timestamps[7]),
+ SearchSource::ProjectName,
+ ),
];
- let doc_next_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
- entity_id: doc_ids[6],
+ let project_next_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
+ entity_id: project_ids[6],
updated_at: timestamps[6],
}));
- let included_doc_names = final_tagged
+ let included_project_names = final_tagged
.iter()
- .filter(|h| h.source == SearchSource::DocumentName)
+ .filter(|h| h.source == SearchSource::ProjectName)
.count();
- let doc_name_count = 10; // Original fetch returned 10
+ let project_name_count = 10; // Original fetch returned 10
- let new_doc_cursor = compute_next_cursor(
- &doc_next_cursor,
- included_doc_names,
- doc_name_count,
- find_last_of_source(&final_tagged, SearchSource::DocumentName),
+ let new_project_cursor = compute_next_cursor(
+ &project_next_cursor,
+ included_project_names,
+ project_name_count,
+ find_last_of_source(&final_tagged, SearchSource::ProjectName),
&SearchCursorOption::NotDone(None),
);
- // Should generate cursor from last included doc (doc_ids[7])
- match new_doc_cursor {
+ // Should generate cursor from last included project (project_ids[7])
+ match new_project_cursor {
SearchCursorOption::NotDone(Some(cursor)) => {
let (id, ts) = cursor.as_updated_at().expect("expected UpdatedAt cursor");
- assert_eq!(id, doc_ids[7]);
+ assert_eq!(id, project_ids[7]);
assert_eq!(ts, timestamps[7]);
}
_ => panic!(
- "Expected cursor from last included doc, got {:?}",
- new_doc_cursor
+ "Expected cursor from last included project, got {:?}",
+ new_project_cursor
),
}
}
@@ -323,27 +335,27 @@ fn test_cursor_logic_pagination_scenario() {
#[test]
fn test_cursor_logic_source_exhausted_scenario() {
// Simulate when a source is exhausted (returned fewer than requested)
- // - Search returned 3 documents (less than page_size of 10)
+ // - Search returned 3 projects (less than page_size of 10)
// - All 3 made it into the final page
// - Cursor should be Done since source is exhausted
let final_tagged: Vec<TaggedSearchHit> = vec![
- make_tagged_hit(Uuid::new_v4(), Some(ts(3000)), SearchSource::DocumentName),
- make_tagged_hit(Uuid::new_v4(), Some(ts(2000)), SearchSource::DocumentName),
- make_tagged_hit(Uuid::new_v4(), Some(ts(1000)), SearchSource::DocumentName),
+ make_tagged_hit(Uuid::new_v4(), Some(ts(3000)), SearchSource::ProjectName),
+ make_tagged_hit(Uuid::new_v4(), Some(ts(2000)), SearchSource::ProjectName),
+ make_tagged_hit(Uuid::new_v4(), Some(ts(1000)), SearchSource::ProjectName),
];
- let doc_next_cursor = SearchCursorOption::Done; // Search says done
+ let project_next_cursor = SearchCursorOption::Done; // Search says done
- let new_doc_cursor = compute_next_cursor(
- &doc_next_cursor,
+ let new_project_cursor = compute_next_cursor(
+ &project_next_cursor,
3, // all included
3, // all returned
- find_last_of_source(&final_tagged, SearchSource::DocumentName),
+ find_last_of_source(&final_tagged, SearchSource::ProjectName),
&SearchCursorOption::NotDone(None),
);
- assert!(new_doc_cursor.is_done());
+ assert!(new_project_cursor.is_done());
}
// ==================== CRM source cursor scenarios ====================
@@ -365,7 +377,7 @@ fn test_cursor_logic_crm_starved_preserves_cursor() {
// Final page: all non-CRM (CRM starved out by newer doc/chat hits).
let final_tagged: Vec<TaggedSearchHit> = vec![
- make_tagged_hit(Uuid::new_v4(), Some(ts(9000)), SearchSource::DocumentName),
+ make_tagged_hit(Uuid::new_v4(), Some(ts(9000)), SearchSource::ProjectName),
make_tagged_hit(Uuid::new_v4(), Some(ts(8000)), SearchSource::ChatName),
];
@@ -408,7 +420,7 @@ fn test_cursor_logic_crm_included_advances_cursor() {
let crm_id = Uuid::new_v4();
let crm_ts = ts(7000);
let final_tagged: Vec<TaggedSearchHit> = vec![
- make_tagged_hit(Uuid::new_v4(), Some(ts(9000)), SearchSource::DocumentName),
+ make_tagged_hit(Uuid::new_v4(), Some(ts(9000)), SearchSource::ProjectName),
make_tagged_hit(crm_id, Some(crm_ts), SearchSource::CrmCompany),
];