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): very basic email multi term (#1951)

gbirman0c01e64d2590
diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
index 7a207ed6fb..c8c59a907a 100644
--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
@@ -120,14 +120,14 @@ export const createSearchState = ({
const searchUnifiedNameContentRequest = createMemo(
(): UnifiedSearchRequest => {
- const terms = debouncedSearchForService();
+ const query = debouncedSearchForService();
const include = unifiedSearchIncludeArray();
const filters = searchFilters();
return {
search_on: 'name_content',
match_type: 'partial',
- terms: terms.length > 0 ? [terms] : undefined,
+ query,
include,
filters,
};
diff --git a/js/app/packages/core/signal/search.ts b/js/app/packages/core/signal/search.ts
deleted file mode 100644
index 0b2fc3c1b2..0000000000
--- a/js/app/packages/core/signal/search.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
-import { isErr } from '@core/util/maybeResult';
-import { searchClient } from '@service-search/client';
-import type { UnifiedSearchResponse } from '@service-search/generated/models/unifiedSearchResponse';
-import { makeAbortable } from '@solid-primitives/resource';
-import { createMemo, createResource } from 'solid-js';
-
-// TODO: would be nice to rework things to all use createSearchResource again... sigh
-export function createUnifiedSearchResource(
- searchTerm: () => string,
- cursor: () => string | null = () => null
-) {
- const combined = () => [searchTerm(), cursor()] as const;
- const [signal, , filterError] = makeAbortable();
-
- return createResource(combined, async ([term, cursorValue]) => {
- if (!ENABLE_SEARCH_SERVICE) return null;
- if (term.length < 3) return null;
-
- try {
- const result = await searchClient.search(
- {
- request: {
- search_on: 'content',
- match_type: 'partial',
- terms: [term],
- filters: {
- channel: {},
- chat: {},
- document: {},
- email: {},
- project: {},
- },
- },
- params: { cursor: cursorValue, page_size: 10 },
- },
- { signal: signal() }
- );
- if (isErr(result)) {
- console.error('Failed to get search query');
- return null;
- }
- const [, data] = result;
- return data;
- } catch (err) {
- filterError(err);
- return null;
- }
- });
-}
-
-export function useSearch(
- searchTerm: () => string,
- cursor: () => string | null = () => null
-) {
- const [resource] = createUnifiedSearchResource(searchTerm, cursor);
- return createMemo((): UnifiedSearchResponse | undefined => {
- const latest = resource?.latest;
- if (!latest) return undefined;
- return latest;
- });
-}
diff --git a/js/app/packages/queries/soup/search.ts b/js/app/packages/queries/soup/search.ts
index 2944df3ba2..47a8a36f8b 100644
--- a/js/app/packages/queries/soup/search.ts
+++ b/js/app/packages/queries/soup/search.ts
@@ -36,36 +36,17 @@ export const useSearchSoupQuery = (
return {
...body,
query: body.query?.trim(),
- terms: body.terms?.map((t) => t.trim()),
};
});
- const terms = createMemo(() => {
- const query = request().query;
- const hasQuery = query && query.length > 0;
- const terms = request().terms;
- const hasTerms = terms && terms.length > 0;
- if (hasTerms && hasQuery) {
- console.error('Cannot have both query and terms');
- return [];
- }
- if (hasTerms) {
- return terms;
- }
- if (hasQuery) {
- return [query];
- }
- return [];
- });
-
- const validSearchTerms = createMemo(() => {
- return terms().length > 0 && terms().every(validateSearchServiceText);
+ const validSearch = createMemo(() => {
+ return validateSearchServiceText(request().query);
});
const enabled = createMemo(() => {
if (options?.().enabled === false) return false;
- return ENABLE_SEARCH_SERVICE && validSearchTerms();
+ return ENABLE_SEARCH_SERVICE && validSearch();
});
const mapSearchResponseItem = useSearchResponseItemMapper();
@@ -94,7 +75,7 @@ export const useSearchSoupQuery = (
};
},
select: (data) => {
- const searchQuery = terms()[0];
+ const searchQuery = request().query;
return data.pages.flatMap((page) => {
return page.results
.map((result) => mapSearchResponseItem(result, searchQuery))
diff --git a/js/app/packages/queries/soup/useFullTextSearch.ts b/js/app/packages/queries/soup/useFullTextSearch.ts
index ebd66971a6..1ba51fc24b 100644
--- a/js/app/packages/queries/soup/useFullTextSearch.ts
+++ b/js/app/packages/queries/soup/useFullTextSearch.ts
@@ -1,6 +1,6 @@
import { debouncedDependent } from '@core/util/debounce';
import type { Accessor } from 'solid-js';
-import { useSearchSoupQuery, validateSearchServiceText } from './search';
+import { useSearchSoupQuery } from './search';
/**
* Minimal full-text search hook for contexts that just need a query string →
@@ -11,21 +11,15 @@ import { useSearchSoupQuery, validateSearchServiceText } from './search';
export function useFullTextSearch(query: Accessor<string>) {
const debouncedQuery = debouncedDependent(query, 300);
- const searchQuery = useSearchSoupQuery(
- () => ({
- params: { page_size: 100 },
- body: {
- search_on: 'name_content',
- match_type: 'partial',
- terms:
- debouncedQuery().trim().length > 0
- ? [debouncedQuery().trim()]
- : undefined,
- include: [],
- },
- }),
- () => ({ enabled: validateSearchServiceText(debouncedQuery()) })
- );
+ const searchQuery = useSearchSoupQuery(() => ({
+ params: { page_size: 100 },
+ body: {
+ search_on: 'name_content',
+ match_type: 'partial',
+ query: debouncedQuery(),
+ include: [],
+ },
+ }));
return {
results: () => searchQuery.data ?? [],
diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.ts
index bc7287f8e0..fc66d471fa 100644
--- a/js/app/packages/service-clients/service-search/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts
@@ -201,8 +201,6 @@ export * from './unifiedSearchParams';
export * from './unifiedSearchRequest';
export * from './unifiedSearchRequestCollapse';
export * from './unifiedSearchRequestFilters';
-export * from './unifiedSearchRequestQuery';
-export * from './unifiedSearchRequestTerms';
export * from './unifiedSearchResponse';
export * from './unifiedSearchResponseItem';
export * from './unifiedSearchResponseItemOneOf';
diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts
index d75b055cc8..570ea36edb 100644
--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts
@@ -10,8 +10,6 @@ import type { SearchOn } from './searchOn';
import type { UnifiedSearchIndex } from './unifiedSearchIndex';
import type { UnifiedSearchRequestCollapse } from './unifiedSearchRequestCollapse';
import type { UnifiedSearchRequestFilters } from './unifiedSearchRequestFilters';
-import type { UnifiedSearchRequestQuery } from './unifiedSearchRequestQuery';
-import type { UnifiedSearchRequestTerms } from './unifiedSearchRequestTerms';
export interface UnifiedSearchRequest {
collapse?: UnifiedSearchRequestCollapse;
@@ -20,9 +18,8 @@ export interface UnifiedSearchRequest {
include?: UnifiedSearchIndex[];
/** How to match the search terms. 'exact' for precise case-sensitive phrase matches, 'partial' for prefix/partial matches. REQUIRED field. */
match_type: MatchType;
- query?: UnifiedSearchRequestQuery;
+ /** The search query string. Must be at least 3 characters. */
+ query: string;
/** Fields to search on (Name, Content, NameContent). Defaults to Content */
search_on?: SearchOn;
- /** Multiple distinct search terms as separate strings. Use this for keyword-based searches where you want to find content containing any of these terms. Each term must be at least 3 characters (shorter terms are automatically filtered out). Examples: ['machine', 'learning', 'algorithms'], ['project', 'status', 'update']. `null` this field if searching without text terms to search all. This field matches query string against both name and content. */
- terms?: UnifiedSearchRequestTerms;
}
diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestQuery.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestQuery.ts
deleted file mode 100644
index fe73590b77..0000000000
--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestQuery.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * search_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type UnifiedSearchRequestQuery = string | null;
diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestTerms.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestTerms.ts
deleted file mode 100644
index abf5669e8c..0000000000
--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestTerms.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * search_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Multiple distinct search terms as separate strings. Use this for keyword-based searches where you want to find content containing any of these terms. Each term must be at least 3 characters (shorter terms are automatically filtered out). Examples: ['machine', 'learning', 'algorithms'], ['project', 'status', 'update']. `null` this field if searching without text terms to search all. This field matches query string against both name and content.
- */
-export type UnifiedSearchRequestTerms = string[] | null;
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index 94dd69e4c4..2f46fb476d 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -2863,7 +2863,7 @@
},
"UnifiedSearchRequest": {
"type": "object",
- "required": ["match_type"],
+ "required": ["query", "match_type"],
"properties": {
"collapse": {
"type": ["boolean", "null"]
@@ -2891,18 +2891,12 @@
"description": "How to match the search terms. 'exact' for precise case-sensitive phrase matches, 'partial' for prefix/partial matches. REQUIRED field."
},
"query": {
- "type": ["string", "null"]
+ "type": "string",
+ "description": "The search query string. Must be at least 3 characters."
},
"search_on": {
"$ref": "#/components/schemas/SearchOn",
"description": "Fields to search on (Name, Content, NameContent). Defaults to Content"
- },
- "terms": {
- "type": ["array", "null"],
- "items": {
- "type": "string"
- },
- "description": "Multiple distinct search terms as separate strings. Use this for keyword-based searches where you want to find content containing any of these terms. Each term must be at least 3 characters (shorter terms are automatically filtered out). Examples: ['machine', 'learning', 'algorithms'], ['project', 'status', 'update']. `null` this field if searching without text terms to search all. This field matches query string against both name and content."
}
}
},
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
index 74da65c6bf..d5c21b57d1 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
@@ -50,8 +50,7 @@ impl AsyncTool<Arc<SearchServiceClient>> for ContentSearch {
}
let search_request = UnifiedSearchRequest {
- query: Some(self.query.to_owned()),
- terms: None,
+ query: self.query.to_owned(),
match_type: MatchType::Partial,
filters: Some(UnifiedSearchFilters {
email: Some(EmailFilters {
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
index 42829dff4d..a57070f058 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
@@ -50,8 +50,7 @@ impl AsyncTool<Arc<SearchServiceClient>> for NameSearch {
}
let search_request = UnifiedSearchRequest {
- query: Some(self.name.to_owned()),
- terms: None,
+ query: self.name.to_owned(),
match_type: MatchType::Partial,
filters: Some(UnifiedSearchFilters {
email: Some(EmailFilters {
diff --git a/rust/cloud-storage/models_search/src/unified.rs b/rust/cloud-storage/models_search/src/unified.rs
index 50afeb8eee..acd6f0477a 100644
--- a/rust/cloud-storage/models_search/src/unified.rs
+++ b/rust/cloud-storage/models_search/src/unified.rs
@@ -27,14 +27,11 @@ pub enum UnifiedSearchIndex {
Projects,
}
-// TODO: query, terms, match_type are common to all requests. consolidate.
+// TODO: query, match_type are common to all requests. consolidate.
#[derive(Debug, Serialize, Deserialize, ToSchema, Clone, JsonSchema)]
pub struct UnifiedSearchRequest {
- #[schemars(skip)]
- pub query: Option<String>,
-
- /// Multiple distinct search terms as separate strings. Use this for keyword-based searches where you want to find content containing any of these terms. Each term must be at least 3 characters (shorter terms are automatically filtered out). Examples: ['machine', 'learning', 'algorithms'], ['project', 'status', 'update']. `null` this field if searching without text terms to search all. This field matches query string against both name and content.
- pub terms: Option<Vec<String>>,
+ /// The search query string. Must be at least 3 characters.
+ pub query: String,
/// How to match the search terms. 'exact' for precise case-sensitive phrase matches, 'partial' for prefix/partial matches. REQUIRED field.
pub match_type: MatchType,
diff --git a/rust/cloud-storage/opensearch_client/examples/unified_opensearch_query.rs b/rust/cloud-storage/opensearch_client/examples/unified_opensearch_query.rs
index 4e338e141c..b51b18a49e 100644
--- a/rust/cloud-storage/opensearch_client/examples/unified_opensearch_query.rs
+++ b/rust/cloud-storage/opensearch_client/examples/unified_opensearch_query.rs
@@ -6,7 +6,6 @@ use opensearch_client::search::unified::{UnifiedEmailSearchArgs, UnifiedSearchAr
fn main() {
let args = UnifiedSearchArgs {
- terms: vec!["hello re".to_string()],
user_id: "macro|[email protected]".to_string(),
page: 0,
page_size: 10,
@@ -14,7 +13,10 @@ fn main() {
collapse: false,
cursor: SearchCursorOption::NotDone(None),
search_indices: HashSet::from([SearchEntityType::Emails]),
- email_search_args: UnifiedEmailSearchArgs::default(),
+ email_search_args: UnifiedEmailSearchArgs {
+ terms: vec!["hello re".to_string()],
+ ..Default::default()
+ },
..Default::default()
};
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rs
index e146d7791c..9c8a9d40cf 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs
@@ -7,7 +7,7 @@ use crate::{
};
use models_opensearch::SearchEntityType;
-use opensearch_query_builder::{BoolQuery, BoolQueryBuilder, QueryType};
+use opensearch_query_builder::{BoolQuery, BoolQueryBuilder, QueryType, SimpleQueryStringQuery};
pub(crate) struct EmailSearchConfig;
@@ -17,6 +17,41 @@ impl SearchQueryConfig for EmailSearchConfig {
const ENTITY_INDEX: SearchEntityType = SearchEntityType::Emails;
}
+/// The fields to search across with simple_query_string for email search.
+const EMAIL_SIMPLE_QUERY_FIELDS: &[&str] = &[
+ "sender",
+ "reply_to",
+ "recipients",
+ "cc",
+ "bcc",
+ "subject",
+ "content",
+ "sender_name",
+ "recipient_names",
+ "cc_names",
+ "bcc_names",
+];
+
+/// Transforms search terms into a simple_query_string query string.
+/// Single-word terms become `(term | term@*)` so they match both text fields
+/// and keyword email-address fields. Multi-word terms (containing spaces) skip
+/// the `@*` pattern since email addresses never contain spaces.
+/// The email pattern is lowercased because email addresses are case-insensitive.
+/// Terms are ANDed together with `+`.
+fn build_simple_query_string(terms: &[String]) -> String {
+ terms
+ .iter()
+ .map(|term| {
+ if term.contains(' ') {
+ format!("({})", term)
+ } else {
+ format!("({} | {}@*)", term, term.to_lowercase())
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" + ")
+}
+
pub(crate) struct EmailQueryBuilder {
inner: SearchQueryBuilder<EmailSearchConfig>,
/// link ids to query over
@@ -108,6 +143,18 @@ impl EmailQueryBuilder {
pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
let mut content_bool_query = self.inner.build_content_bool_query()?;
+ // For multi-term searches, replace the default content-only must clause with a
+ // simple_query_string that searches across all email fields (addresses, names, subject, content)
+ if self.inner.terms.len() > 1 {
+ let query_string = build_simple_query_string(&self.inner.terms);
+ let sqs = SimpleQueryStringQuery::new(
+ query_string,
+ EMAIL_SIMPLE_QUERY_FIELDS.iter().copied(),
+ )
+ .default_operator("AND");
+ content_bool_query.set_must(sqs.into());
+ }
+
// CUSTOM ATTRIBUTES SECTION
// If link_ids are provided, add them to the query
if !self.link_ids.is_empty() {
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
index 5b1631b7fd..569fdc5637 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
@@ -1,6 +1,76 @@
use super::*;
use opensearch_query_builder::ToOpenSearchJson;
+#[test]
+fn test_build_simple_query_string_single_term() {
+ let result = build_simple_query_string(&["hello".to_string()]);
+ assert_eq!(result, "(hello | hello@*)");
+}
+
+#[test]
+fn test_build_simple_query_string_multiple_terms() {
+ let result = build_simple_query_string(&["hello".to_string(), "test".to_string()]);
+ assert_eq!(result, "(hello | hello@*) + (test | test@*)");
+}
+
+#[test]
+fn test_build_simple_query_string_multi_word_term_skips_email_pattern() {
+ let result = build_simple_query_string(&["hi there".to_string()]);
+ assert_eq!(result, "(hi there)");
+}
+
+#[test]
+fn test_build_simple_query_string_uppercase_lowercased_for_email() {
+ let result = build_simple_query_string(&["Teo".to_string()]);
+ assert_eq!(result, "(Teo | teo@*)");
+}
+
+#[test]
+fn test_build_simple_query_string_mixed_single_and_multi_word() {
+ let result = build_simple_query_string(&["Teo".to_string(), "hello world".to_string()]);
+ assert_eq!(result, "(Teo | teo@*) + (hello world)");
+}
+
+#[test]
+fn test_email_search_args_build_injects_simple_query_string() -> anyhow::Result<()> {
+ let builder: EmailQueryBuilder = EmailSearchArgs {
+ terms: vec!["hello".to_string(), "test".to_string()],
+ user_id: "macro|[email protected]".to_string(),
+ thread_ids: vec![],
+ link_ids: vec![],
+ sender: vec![],
+ cc: vec![],
+ bcc: vec![],
+ recipients: vec![],
+ include_labels: vec![],
+ exclude_labels: vec![],
+ importance: None,
+ page: 0,
+ page_size: 20,
+ match_type: "partial".to_string(),
+ collapse: true,
+ ids_only: false,
+ }
+ .into();
+
+ let json = builder.build_bool_query()?.build().to_json();
+ let must = &json["bool"]["must"];
+ let sqc = &must[0]["simple_query_string"];
+
+ assert_eq!(sqc["query"], "(hello | hello@*) + (test | test@*)");
+ assert_eq!(sqc["default_operator"], "AND");
+
+ let fields = sqc["fields"].as_array().unwrap();
+ assert!(fields.contains(&serde_json::json!("sender")));
+ assert!(fields.contains(&serde_json::json!("reply_to")));
+ assert!(fields.contains(&serde_json::json!("content")));
+ assert!(fields.contains(&serde_json::json!("subject")));
+ assert!(fields.contains(&serde_json::json!("sender_name")));
+ assert!(fields.contains(&serde_json::json!("recipient_names")));
+
+ Ok(())
+}
+
#[test]
fn test_build_bool_query() -> anyhow::Result<()> {
let builder = EmailQueryBuilder::new(vec!["test".to_string()])
diff --git a/rust/cloud-storage/opensearch_client/src/search/query.rs b/rust/cloud-storage/opensearch_client/src/search/query.rs
index f4d8d20aae..6db431acf8 100644
--- a/rust/cloud-storage/opensearch_client/src/search/query.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/query.rs
@@ -122,10 +122,6 @@ pub(crate) fn generate_terms_must_query<'a>(
field: &'a str,
terms: impl Into<Cow<'a, [&'a str]>>,
) -> QueryType<'a> {
- let mut terms_must_query = BoolQueryBuilder::new();
-
- terms_must_query.minimum_should_match(1);
-
let terms = terms.into();
// Map terms to queries
@@ -140,19 +136,20 @@ pub(crate) fn generate_terms_must_query<'a>(
})
.collect();
- // If we only have 1 query returned, we can just return that singular query
- // to go into the main bool must
if queries.len() == 1 {
return queries[0].clone();
}
- // Otherwise, we need to add all the queries to a new bool should in order to properly search
- // over multiple terms
+ // Use OR (should) across terms because document content is split across
+ // multiple OpenSearch nodes. AND filtering happens post-collapse at the
+ // application layer.
+ let mut terms_should_query = BoolQueryBuilder::new();
+ terms_should_query.minimum_should_match(1);
for query in queries {
- terms_must_query.should(query);
+ terms_should_query.should(query);
}
- terms_must_query.build().into()
+ terms_should_query.build().into()
}
#[cfg(test)]
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index b46d4eb83e..47c10c0bab 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -41,7 +41,6 @@ impl UnifiedSearchArgs {
#[derive(Debug, Default, Clone)]
pub struct UnifiedSearchArgs {
- pub terms: Vec<String>,
pub user_id: String,
pub page: u32,
pub page_size: u32,
@@ -64,7 +63,7 @@ pub struct UnifiedSearchArgs {
impl From<UnifiedSearchArgs> for DocumentSearchArgs {
fn from(args: UnifiedSearchArgs) -> Self {
DocumentSearchArgs {
- terms: args.terms,
+ terms: args.document_search_args.terms,
user_id: args.user_id,
page: args.page,
page_size: args.page_size,
@@ -79,7 +78,7 @@ impl From<UnifiedSearchArgs> for DocumentSearchArgs {
impl From<UnifiedSearchArgs> for EmailSearchArgs {
fn from(args: UnifiedSearchArgs) -> Self {
EmailSearchArgs {
- terms: args.terms,
+ terms: args.email_search_args.terms,
user_id: args.user_id,
page: args.page,
page_size: args.page_size,
@@ -102,7 +101,7 @@ impl From<UnifiedSearchArgs> for EmailSearchArgs {
impl From<UnifiedSearchArgs> for ChannelMessageSearchArgs {
fn from(args: UnifiedSearchArgs) -> Self {
ChannelMessageSearchArgs {
- terms: args.terms,
+ terms: args.channel_message_search_args.terms,
user_id: args.user_id,
page: args.page,
page_size: args.page_size,
@@ -120,7 +119,7 @@ impl From<UnifiedSearchArgs> for ChannelMessageSearchArgs {
impl From<UnifiedSearchArgs> for ChatSearchArgs {
fn from(args: UnifiedSearchArgs) -> Self {
ChatSearchArgs {
- terms: args.terms,
+ terms: args.chat_search_args.terms,
user_id: args.user_id,
page: args.page,
page_size: args.page_size,
@@ -135,6 +134,7 @@ impl From<UnifiedSearchArgs> for ChatSearchArgs {
#[derive(Debug, Default, Clone)]
pub struct UnifiedChatSearchArgs {
+ pub terms: Vec<String>,
pub chat_ids: Vec<String>,
pub role: Vec<String>,
pub ids_only: bool,
@@ -142,12 +142,14 @@ pub struct UnifiedChatSearchArgs {
#[derive(Debug, Default, Clone)]
pub struct UnifiedDocumentSearchArgs {
+ pub terms: Vec<String>,
pub document_ids: Vec<String>,
pub ids_only: bool,
}
#[derive(Debug, Default, Clone)]
pub struct UnifiedEmailSearchArgs {
+ pub terms: Vec<String>,
pub thread_ids: Vec<String>,
pub link_ids: Vec<String>,
pub sender: Vec<String>,
@@ -161,6 +163,7 @@ pub struct UnifiedEmailSearchArgs {
#[derive(Debug, Default, Clone)]
pub struct UnifiedChannelMessageSearchArgs {
+ pub terms: Vec<String>,
pub channel_ids: Vec<String>,
pub thread_ids: Vec<String>,
pub mentions: Vec<String>,
@@ -447,7 +450,7 @@ pub(crate) async fn search_unified(
.search_indices
.iter()
.filter(|i| **i != SearchEntityType::Projects)
- .map(|i| i.as_ref())
+ .map(|i| i.index_name())
.collect();
// After we filter out invalid search entities if we have nothing we should return that the cursor is exhausted
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 cde17a0da5..4543004874 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -415,7 +415,6 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
]
.into_iter()
.collect(),
- terms: vec!["test".to_string()],
user_id: "user".to_string(),
page: 1,
page_size: 20,
@@ -423,10 +422,12 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
collapse: true,
document_search_args: UnifiedDocumentSearchArgs {
+ terms: vec!["test".to_string()],
document_ids: vec!["id1".to_string(), "id2".to_string()],
ids_only: false,
},
email_search_args: UnifiedEmailSearchArgs {
+ terms: vec!["test".to_string()],
thread_ids: vec!["id1".to_string(), "id2".to_string()],
link_ids: vec!["id1".to_string(), "id2".to_string()],
sender: vec!["id1".to_string(), "id2".to_string()],
@@ -436,12 +437,14 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
..Default::default()
},
channel_message_search_args: UnifiedChannelMessageSearchArgs {
+ terms: vec!["test".to_string()],
channel_ids: vec!["id1".to_string(), "id2".to_string()],
thread_ids: vec!["id1".to_string(), "id2".to_string()],
mentions: vec!["id1".to_string(), "id2".to_string()],
sender_ids: vec!["id1".to_string(), "id2".to_string()],
},
chat_search_args: UnifiedChatSearchArgs {
+ terms: vec!["test".to_string()],
chat_ids: vec!["id1".to_string(), "id2".to_string()],
role: vec!["id1".to_string(), "id2".to_string()],
ids_only: false,
@@ -651,7 +654,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
]
}
}
- ],
+ ]
}
},
{
@@ -784,7 +787,6 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
]
.into_iter()
.collect(),
- terms: vec!["test".to_string()],
user_id: "user".to_string(),
page: 1,
page_size: 20,
@@ -792,10 +794,12 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
collapse: true,
document_search_args: UnifiedDocumentSearchArgs {
+ terms: vec!["test".to_string()],
document_ids: vec!["id1".to_string(), "id2".to_string()],
ids_only: false,
},
email_search_args: UnifiedEmailSearchArgs {
+ terms: vec!["test".to_string()],
thread_ids: vec!["id1".to_string(), "id2".to_string()],
link_ids: vec!["id1".to_string(), "id2".to_string()],
sender: vec!["id1".to_string(), "id2".to_string()],
@@ -805,12 +809,14 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
..Default::default()
},
channel_message_search_args: UnifiedChannelMessageSearchArgs {
+ terms: vec!["test".to_string()],
channel_ids: vec!["id1".to_string(), "id2".to_string()],
thread_ids: vec!["id1".to_string(), "id2".to_string()],
mentions: vec!["id1".to_string(), "id2".to_string()],
sender_ids: vec!["id1".to_string(), "id2".to_string()],
},
chat_search_args: UnifiedChatSearchArgs {
+ terms: vec!["test".to_string()],
chat_ids: vec!["id1".to_string(), "id2".to_string()],
role: vec!["id1".to_string(), "id2".to_string()],
ids_only: false,
@@ -832,7 +838,6 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
let unified_search_args = UnifiedSearchArgs {
search_indices: vec![SearchEntityType::Documents].into_iter().collect(),
- terms: vec!["test".to_string()],
user_id: "user".to_string(),
page: 1,
page_size: 20,
@@ -840,6 +845,7 @@ fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
collapse: true,
document_search_args: UnifiedDocumentSearchArgs {
+ terms: vec!["test".to_string()],
document_ids: vec!["id1".to_string(), "id2".to_string()],
ids_only: false,
},
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query.rs b/rust/cloud-storage/opensearch_query_builder/src/query.rs
index 2ddfbaf65c..ab9ce329fe 100644
--- a/rust/cloud-storage/opensearch_query_builder/src/query.rs
+++ b/rust/cloud-storage/opensearch_query_builder/src/query.rs
@@ -9,6 +9,7 @@ mod match_phrase_prefix;
mod match_query;
mod range;
mod regexp;
+mod simple_query_string;
mod term;
mod terms;
mod wildcard;
@@ -21,6 +22,7 @@ pub use match_query::*;
pub use range::*;
pub use regexp::*;
use serde_json::Value;
+pub use simple_query_string::*;
pub use term::*;
pub use terms::*;
pub use wildcard::*;
@@ -51,6 +53,8 @@ pub enum QueryType<'a> {
Terms(TermsQuery<'a>),
/// Wildcard query
WildCard(WildcardQuery<'a>),
+ /// Simple query string query
+ SimpleQueryString(SimpleQueryStringQuery<'a>),
}
impl<'a> ToOpenSearchJson for QueryType<'a> {
@@ -66,6 +70,7 @@ impl<'a> ToOpenSearchJson for QueryType<'a> {
QueryType::Range(range) => range.to_json(),
QueryType::WildCard(wildcard_query) => wildcard_query.to_json(),
QueryType::Regexp(regexp_query) => regexp_query.to_json(),
+ QueryType::SimpleQueryString(simple_query_string) => simple_query_string.to_json(),
}
}
}
@@ -121,6 +126,14 @@ impl<'a> QueryType<'a> {
RangeQueryBuilder::new(field)
}
+ /// Convenience method for creating a simple query string query
+ pub fn simple_query_string(
+ query: impl Into<Cow<'a, str>>,
+ fields: impl IntoIterator<Item = impl Into<Cow<'a, str>>>,
+ ) -> Self {
+ QueryType::SimpleQueryString(SimpleQueryStringQuery::new(query, fields))
+ }
+
/// Convenience method for starting a function score query
pub fn function_score() -> FunctionScoreQueryBuilder<'a> {
FunctionScoreQueryBuilder::new()
@@ -143,6 +156,7 @@ impl<'a> QueryType<'a> {
QueryType::Term(term) => QueryType::Term(term.to_owned()),
QueryType::Terms(terms) => QueryType::Terms(terms.to_owned()),
QueryType::WildCard(wildcard) => QueryType::WildCard(wildcard.to_owned()),
+ QueryType::SimpleQueryString(sqs) => QueryType::SimpleQueryString(sqs.to_owned()),
}
}
}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/bool.rs b/rust/cloud-storage/opensearch_query_builder/src/query/bool.rs
index 10a11c3534..2a9a09d137 100644
--- a/rust/cloud-storage/opensearch_query_builder/src/query/bool.rs
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/bool.rs
@@ -153,6 +153,12 @@ impl<'a> BoolQueryBuilder<'a> {
self
}
+ /// Replace all must queries with a single query
+ pub fn set_must(&mut self, query: QueryType<'a>) -> &mut Self {
+ self.must = Cow::Owned(vec![query]);
+ self
+ }
+
/// Add a must not query
pub fn must_not(&mut self, query: QueryType<'a>) -> &mut Self {
self.must_not.to_mut().push(query);
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/simple_query_string.rs b/rust/cloud-storage/opensearch_query_builder/src/query/simple_query_string.rs
new file mode 100644
index 0000000000..c7ec1c78dd
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/simple_query_string.rs
@@ -0,0 +1,92 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Simple Query String Query
+///
+/// Searches across multiple fields using a simple query syntax that supports
+/// operators like `+` (AND), `|` (OR), `-` (NOT), `*` (wildcard), and `()` (grouping).
+#[derive(Debug, Clone, Serialize)]
+pub struct SimpleQueryStringQuery<'a> {
+ /// The query string
+ #[serde(borrow)]
+ pub query: Cow<'a, str>,
+ /// The fields to search
+ pub fields: Vec<Cow<'a, str>>,
+ /// The default operator (AND or OR)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(borrow)]
+ pub default_operator: Option<Cow<'a, str>>,
+}
+
+impl<'a> SimpleQueryStringQuery<'a> {
+ /// Create a new SimpleQueryStringQuery with a query string and fields
+ pub fn new(
+ query: impl Into<Cow<'a, str>>,
+ fields: impl IntoIterator<Item = impl Into<Cow<'a, str>>>,
+ ) -> Self {
+ Self {
+ query: query.into(),
+ fields: fields.into_iter().map(|f| f.into()).collect(),
+ default_operator: None,
+ }
+ }
+
+ /// Set the default operator (AND or OR)
+ pub fn default_operator(mut self, operator: impl Into<Cow<'a, str>>) -> Self {
+ self.default_operator = Some(operator.into());
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> SimpleQueryStringQuery<'static> {
+ SimpleQueryStringQuery {
+ query: Cow::Owned(self.query.to_string()),
+ fields: self
+ .fields
+ .iter()
+ .map(|f| Cow::Owned(f.to_string()))
+ .collect(),
+ default_operator: self
+ .default_operator
+ .as_ref()
+ .map(|o| Cow::Owned(o.to_string())),
+ }
+ }
+}
+
+impl<'a> From<SimpleQueryStringQuery<'a>> for QueryType<'a> {
+ fn from(query: SimpleQueryStringQuery<'a>) -> Self {
+ QueryType::SimpleQueryString(query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for SimpleQueryStringQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut inner = Map::new();
+ inner.insert("query".to_string(), Value::String(self.query.to_string()));
+ inner.insert(
+ "fields".to_string(),
+ Value::Array(
+ self.fields
+ .iter()
+ .map(|f| Value::String(f.to_string()))
+ .collect(),
+ ),
+ );
+
+ if let Some(ref operator) = self.default_operator {
+ inner.insert(
+ "default_operator".to_string(),
+ Value::String(operator.to_string()),
+ );
+ }
+
+ let mut result = Map::new();
+ result.insert("simple_query_string".to_string(), Value::Object(inner));
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs
index 44f1f0c6f2..0c4a3d936f 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs
@@ -51,6 +51,7 @@ impl FilterVariantToSearchArgs for item_filters::DocumentFilters {
Ok(UnifiedDocumentSearchArgs {
document_ids: filter_document_response.document_ids,
ids_only: filter_document_response.ids_only,
+ ..Default::default()
})
}
}
@@ -81,6 +82,7 @@ impl FilterVariantToSearchArgs for item_filters::ChannelFilters {
thread_ids: self.thread_ids.clone(),
mentions: self.mentions.clone(),
sender_ids: self.sender_ids.clone(),
+ ..Default::default()
})
}
}
@@ -105,6 +107,7 @@ impl FilterVariantToSearchArgs for item_filters::ChatFilters {
chat_ids: filter_chat_response.chat_ids,
ids_only: filter_chat_response.ids_only,
role: self.role.clone(),
+ ..Default::default()
})
}
}
@@ -147,8 +150,6 @@ impl FilterVariantToSearchArgs for item_filters::EmailFilters {
Ok(UnifiedEmailSearchArgs::default())
} else {
Ok(UnifiedEmailSearchArgs {
- thread_ids: vec![],
- link_ids: vec![],
sender: self.senders.clone(),
cc: self.cc.clone(),
bcc: self.bcc.clone(),
@@ -156,6 +157,7 @@ impl FilterVariantToSearchArgs for item_filters::EmailFilters {
include_labels: self.include_labels.clone(),
exclude_labels: self.exclude_labels.clone(),
importance: self.importance,
+ ..Default::default()
})
}
}
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 77686aad5b..73133823dd 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
@@ -82,6 +82,35 @@ fn compute_next_cursor(
}
}
+/// Splits search terms by whitespace, preserving double-quoted phrases.
+/// e.g. `["hello world"]` → `["hello", "world"]`
+/// e.g. `[r#""hello world" test"#]` → `["hello world", "test"]`
+fn split_search_terms(terms: &[String]) -> Vec<String> {
+ let joined = terms.join(" ");
+ let mut result = Vec::new();
+ // Regex-free parser: iterate chars, track quoted state
+ let mut current = String::new();
+ let mut in_quotes = false;
+ for c in joined.chars() {
+ match c {
+ '"' => in_quotes = !in_quotes,
+ c if c.is_whitespace() && !in_quotes => {
+ let trimmed = current.trim().to_string();
+ if !trimmed.is_empty() {
+ result.push(trimmed);
+ }
+ current.clear();
+ }
+ _ => current.push(c),
+ }
+ }
+ let trimmed = current.trim().to_string();
+ if !trimmed.is_empty() {
+ result.push(trimmed);
+ }
+ result
+}
+
/// Creates a unified search request and performs the search
/// by calling individual simple search endpoints for each entity type
#[tracing::instrument(skip(ctx, user_context, query_params), fields(user_id = %user_context.user_id), err)]
@@ -127,18 +156,11 @@ pub(in crate::api::search) async fn perform_unified_search(
return Err(SearchError::InvalidPageSize);
}
- let terms: Vec<String> = match (req.terms.clone(), req.query.clone()) {
- (Some(terms), _) => terms.into_iter().filter(|t| t.len() >= 3).collect(),
- (None, Some(query)) if query.len() >= 3 => vec![query],
- (None, Some(_)) => {
- return Err(SearchError::InvalidQuerySize);
- }
- _ => vec![],
- };
-
- if terms.is_empty() {
- return Err(SearchError::NoQueryOrTermsProvided);
+ let query = req.query.trim().to_string();
+ if query.len() < 3 {
+ return Err(SearchError::InvalidQuerySize);
}
+ let terms: Vec<String> = vec![query];
let match_type = req.match_type;
let include = req.include;
@@ -158,13 +180,15 @@ pub(in crate::api::search) async fn perform_unified_search(
let should_include_projects =
include.is_empty() || include.contains(&UnifiedSearchIndex::Projects);
let should_include_emails = include.is_empty() || include.contains(&UnifiedSearchIndex::Emails);
+ let email_terms = split_search_terms(&terms);
+ let is_email_multi_term = email_terms.len() > 1;
// Await all tasks in parallel
let (
- filter_document_response,
- filter_channel_response,
- filter_chat_response,
- filter_email_response,
+ mut filter_document_response,
+ mut filter_channel_response,
+ mut filter_chat_response,
+ mut filter_email_response,
filter_project_response,
) = tokio::try_join!(
doc_filters.filter_to_search_args(
@@ -200,6 +224,13 @@ pub(in crate::api::search) async fn perform_unified_search(
)
.map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;
+ // Set terms on each index's search args
+ // Email gets split terms for multi-field search; other indices get the original query
+ filter_document_response.terms = terms.clone();
+ filter_channel_response.terms = terms.clone();
+ filter_chat_response.terms = terms.clone();
+ filter_email_response.terms = email_terms.clone();
+
// Clone terms for use in name searches
let name_search_term = terms[0].clone();
@@ -240,7 +271,6 @@ pub(in crate::api::search) async fn perform_unified_search(
let content_cursor_for_search = content_cursor.clone();
let unified_search_args = UnifiedSearchArgs {
- terms,
user_id: user_id.as_ref().to_string(),
page: 0, // With cursor-based pagination, we always start from "page 0" relative to cursor
page_size,
@@ -311,7 +341,9 @@ pub(in crate::api::search) async fn perform_unified_search(
}
},
async {
- if should_include_emails {
+ // Skip PG email name/subject search for multi-term queries — OpenSearch
+ // simple_query_string already covers subject and contact fields.
+ if should_include_emails && !is_email_multi_term {
match search_on {
SearchOn::Name | SearchOn::NameContent => {
simple_email::search_names(
@@ -334,7 +366,9 @@ pub(in crate::api::search) async fn perform_unified_search(
}
},
async {
- if should_include_emails {
+ // Skip PG email contact search for multi-term queries — OpenSearch
+ // simple_query_string already covers contact fields.
+ if should_include_emails && !is_email_multi_term {
match search_on {
SearchOn::NameContent => {
simple_email::search_contacts(
@@ -604,7 +638,7 @@ pub async fn handler(
) -> Result<Json<SimpleSearchResponse>, SearchError> {
tracing::info!(
user_id = user_context.user_id,
- terms = ?req.terms,
+ query = ?req.query,
search_on = ?req.search_on,
"simple_unified_search"
);
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 79241b36bf..ffd4b408a5 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
@@ -4,6 +4,67 @@ use models_opensearch::SearchEntityType;
use opensearch_client::search::model::Highlight;
use sqlx::types::Uuid;
+// ==================== Tests for split_search_terms ====================
+
+#[test]
+fn test_split_search_terms_simple() {
+ assert_eq!(
+ split_search_terms(&["hello world".to_string()]),
+ vec!["hello", "world"]
+ );
+}
+
+#[test]
+fn test_split_search_terms_multiple_spaces() {
+ assert_eq!(
+ split_search_terms(&["hello world".to_string()]),
+ vec!["hello", "world"]
+ );
+}
+
+#[test]
+fn test_split_search_terms_single_word() {
+ assert_eq!(split_search_terms(&["hello".to_string()]), vec!["hello"]);
+}
+
+#[test]
+fn test_split_search_terms_strips_quotes() {
+ assert_eq!(
+ split_search_terms(&[r#""hello""#.to_string()]),
+ vec!["hello"]
+ );
+}
+
+#[test]
+fn test_split_search_terms_quoted_phrases() {
+ assert_eq!(
+ split_search_terms(&[r#""hello world" test "foo bar""#.to_string()]),
+ vec!["hello world", "test", "foo bar"]
+ );
+}
+
+#[test]
+fn test_split_search_terms_quoted_mixed_with_unquoted() {
+ assert_eq!(
+ split_search_terms(&[r#"foo "bar" baz"#.to_string()]),
+ vec!["foo", "bar", "baz"]
+ );
+}
+
+#[test]
+fn test_split_search_terms_empty_string() {
+ let result: Vec<String> = split_search_terms(&["".to_string()]);
+ assert!(result.is_empty());
+}
+
+#[test]
+fn test_split_search_terms_leading_trailing_whitespace() {
+ assert_eq!(
+ split_search_terms(&[" hello world ".to_string()]),
+ vec!["hello", "world"]
+ );
+}
+
/// Helper to create a TaggedSearchHit for testing
fn make_tagged_hit(
entity_id: Uuid,
diff --git a/rust/cloud-storage/search_service/src/api/search/unified.rs b/rust/cloud-storage/search_service/src/api/search/unified.rs
index 12f0f7102d..32cf0e1eba 100644
--- a/rust/cloud-storage/search_service/src/api/search/unified.rs
+++ b/rust/cloud-storage/search_service/src/api/search/unified.rs
@@ -44,7 +44,7 @@ pub async fn handler(
) -> Result<Json<UnifiedSearchResponse>, SearchError> {
tracing::info!(
user_id = user_context.user_id,
- terms = ?req.terms,
+ query = ?req.query,
search_on = ?req.search_on,
"unified_search"
);