Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(search): prefix-match text fields for email search (#2778)
gbirman34890505d32e
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 881277782a..1391e78225 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -17,13 +17,13 @@ impl SearchQueryConfig for EmailSearchConfig {const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::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",+/// Keyword-indexed email-address fields. Matched explicitly: a bare word+/// only matches an address with that exact local-part (`alice` → `alice@*`),+/// not addresses that merely start with the characters.+const EMAIL_KEYWORD_FIELDS: &[&str] = &["sender", "reply_to", "recipients", "cc", "bcc"];++/// Text-analyzed fields. Matched as a prefix so `scri` matches `script`.+const EMAIL_TEXT_FIELDS: &[&str] = &["subject","content","sender_name",@@ -32,17 +32,17 @@ const EMAIL_SIMPLE_QUERY_FIELDS: &[&str] = &["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.+/// Builds the simple_query_string over the keyword email-address fields.+/// Single-word terms become `(term | term@*)` — an exact token match OR a+/// local-part match on the address. This deliberately does NOT use a trailing+/// `*` on the bare term, so partial local-parts don't leak across addresses+/// (e.g. `ali` won't match `[email protected]` via this group)./// Email-like terms (containing `@`) are wrapped in quotes to force phrase-/// matching on analyzed text fields — otherwise the standard analyzer tokenizes-/// `[email protected]` into `[hutch, macro, com]`, causing `macro.com` to be-/// highlighted inside unrelated addresses like `[email protected]`.+/// matching — otherwise the standard analyzer would tokenize+/// `[email protected]` into `[alice, example, com]`./// The email pattern is lowercased because email addresses are case-insensitive./// Terms are ANDed together with `+`.-fn build_simple_query_string(terms: &[String]) -> String {+fn build_keyword_query_string(terms: &[String]) -> String {terms.iter().map(|term| {@@ -58,6 +58,32 @@ fn build_simple_query_string(terms: &[String]) -> String {.join(" + ")}+/// Minimum prefix length before we emit a `term*` wildcard. Shorter prefixes+/// expand to too many unique tokens in the index and risk blowing past+/// `max_clause_count`. Under this threshold we fall back to exact token match.+const MIN_PREFIX_LEN: usize = 3;++/// Builds the simple_query_string over the text-analyzed fields.+/// Single-word terms become `term*` so a prefix like `scri` matches the+/// token `script` in subject/content/display-name fields. Terms shorter than+/// `MIN_PREFIX_LEN` fall back to exact match to keep term expansion bounded.+/// Multi-word and `@`-containing terms use grouped / phrase matching.+fn build_text_query_string(terms: &[String]) -> String {+ terms+ .iter()+ .map(|term| {+ if term.contains('@') {+ format!("\"{}\"", term)+ } else if term.contains(' ') || term.chars().count() < MIN_PREFIX_LEN {+ format!("({})", term)+ } else {+ format!("{}*", term)+ }+ })+ .collect::<Vec<_>>()+ .join(" + ")+}+pub(crate) struct EmailQueryBuilder {inner: SearchQueryBuilder<EmailSearchConfig>,/// link ids to query over@@ -166,13 +192,23 @@ impl EmailQueryBuilder {inner.should(title_query);content_bool_query.set_must(inner.build().into());} else {- let query_string = build_simple_query_string(&self.inner.terms);- let sqs = SimpleQueryStringQuery::new(- query_string,- EMAIL_SIMPLE_QUERY_FIELDS.iter().copied(),+ let keyword_sqs = SimpleQueryStringQuery::new(+ build_keyword_query_string(&self.inner.terms),+ EMAIL_KEYWORD_FIELDS.iter().copied(),).default_operator("AND");- content_bool_query.set_must(sqs.into());++ let text_sqs = SimpleQueryStringQuery::new(+ build_text_query_string(&self.inner.terms),+ EMAIL_TEXT_FIELDS.iter().copied(),+ )+ .default_operator("AND");++ let mut combined = BoolQueryBuilder::new();+ combined.minimum_should_match(1);+ combined.should(keyword_sqs.into());+ combined.should(text_sqs.into());+ content_bool_query.set_must(combined.build().into());}// CUSTOM ATTRIBUTES SECTIONdiff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rsindex becea69c1a..bb1a981b42 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -2,52 +2,89 @@ 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()]);+fn test_build_keyword_query_string_single_term() {+ let result = build_keyword_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()]);+fn test_build_keyword_query_string_multiple_terms() {+ let result = build_keyword_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()]);+fn test_build_keyword_query_string_multi_word_term_skips_email_pattern() {+ let result = build_keyword_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()]);+fn test_build_keyword_query_string_uppercase_lowercased_for_email() {+ let result = build_keyword_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()]);+fn test_build_keyword_query_string_mixed_single_and_multi_word() {+ let result = build_keyword_query_string(&["Teo".to_string(), "hello world".to_string()]);assert_eq!(result, "(Teo | teo@*) + (hello world)");}#[test]-fn test_build_simple_query_string_email_term_uses_phrase() {- let result = build_simple_query_string(&["[email protected]".to_string()]);- assert_eq!(result, "\"[email protected]\"");+fn test_build_keyword_query_string_email_term_uses_phrase() {+ let result = build_keyword_query_string(&["[email protected]".to_string()]);+ assert_eq!(result, "\"[email protected]\"");}#[test]-fn test_build_simple_query_string_email_term_mixed_with_word() {- let result = build_simple_query_string(&["[email protected]".to_string(), "review".to_string()]);- assert_eq!(result, "\"[email protected]\" + (review | review@*)");+fn test_build_keyword_query_string_email_term_mixed_with_word() {+ let result =+ build_keyword_query_string(&["[email protected]".to_string(), "review".to_string()]);+ assert_eq!(result, "\"[email protected]\" + (review | review@*)");+}++#[test]+fn test_build_text_query_string_single_term_is_prefix() {+ let result = build_text_query_string(&["scri".to_string()]);+ assert_eq!(result, "scri*");+}++#[test]+fn test_build_text_query_string_multiple_terms_are_prefixed_and_anded() {+ let result = build_text_query_string(&["scri".to_string(), "test".to_string()]);+ assert_eq!(result, "scri* + test*");+}++#[test]+fn test_build_text_query_string_multi_word_term_uses_group() {+ let result = build_text_query_string(&["hi there".to_string()]);+ assert_eq!(result, "(hi there)");+}++#[test]+fn test_build_text_query_string_email_term_uses_phrase() {+ let result = build_text_query_string(&["[email protected]".to_string()]);+ assert_eq!(result, "\"[email protected]\"");+}++#[test]+fn test_build_text_query_string_short_term_skips_prefix() {+ let result = build_text_query_string(&["ab".to_string()]);+ assert_eq!(result, "(ab)");+}++#[test]+fn test_build_text_query_string_three_char_term_gets_prefix() {+ let result = build_text_query_string(&["abc".to_string()]);+ assert_eq!(result, "abc*");}#[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(),+ user_id: "macro|[email protected]".to_string(),thread_ids: vec![],link_ids: vec![],sender: vec![],@@ -67,19 +104,48 @@ fn test_email_search_args_build_injects_simple_query_string() -> anyhow::Result<.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 should = json["bool"]["must"][0]["bool"]["should"]+ .as_array()+ .unwrap();+ assert_eq!(json["bool"]["must"][0]["bool"]["minimum_should_match"], 1);+ assert_eq!(should.len(), 2);- 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")));+ let keyword_sqs = should+ .iter()+ .map(|s| &s["simple_query_string"])+ .find(|s| {+ s["fields"]+ .as_array()+ .is_some_and(|f| f.contains(&serde_json::json!("sender")))+ })+ .unwrap();+ assert_eq!(keyword_sqs["query"], "(hello | hello@*) + (test | test@*)");+ assert_eq!(keyword_sqs["default_operator"], "AND");+ let keyword_fields = keyword_sqs["fields"].as_array().unwrap();+ assert!(keyword_fields.contains(&serde_json::json!("sender")));+ assert!(keyword_fields.contains(&serde_json::json!("reply_to")));+ assert!(keyword_fields.contains(&serde_json::json!("recipients")));+ assert!(keyword_fields.contains(&serde_json::json!("cc")));+ assert!(keyword_fields.contains(&serde_json::json!("bcc")));+ assert!(!keyword_fields.contains(&serde_json::json!("subject")));++ let text_sqs = should+ .iter()+ .map(|s| &s["simple_query_string"])+ .find(|s| {+ s["fields"]+ .as_array()+ .is_some_and(|f| f.contains(&serde_json::json!("subject")))+ })+ .unwrap();+ assert_eq!(text_sqs["query"], "hello* + test*");+ assert_eq!(text_sqs["default_operator"], "AND");+ let text_fields = text_sqs["fields"].as_array().unwrap();+ assert!(text_fields.contains(&serde_json::json!("subject")));+ assert!(text_fields.contains(&serde_json::json!("content")));+ assert!(text_fields.contains(&serde_json::json!("sender_name")));+ assert!(text_fields.contains(&serde_json::json!("recipient_names")));+ assert!(!text_fields.contains(&serde_json::json!("sender")));Ok(())}@@ -150,10 +216,24 @@ fn test_build_bool_query() -> anyhow::Result<()> {],"must": [{- "simple_query_string": {- "default_operator": "AND",- "fields": ["sender", "reply_to", "recipients", "cc", "bcc", "subject", "content", "sender_name", "recipient_names", "cc_names", "bcc_names"],- "query": "(test | test@*)"+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "simple_query_string": {+ "default_operator": "AND",+ "fields": ["sender", "reply_to", "recipients", "cc", "bcc"],+ "query": "(test | test@*)"+ }+ },+ {+ "simple_query_string": {+ "default_operator": "AND",+ "fields": ["subject", "content", "sender_name", "recipient_names", "cc_names", "bcc_names"],+ "query": "test*"+ }+ }+ ]}}]diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rsindex 92fb740454..3daf4a290a 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs@@ -647,10 +647,24 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {],"must": [{- "simple_query_string": {- "default_operator": "AND",- "fields": ["sender", "reply_to", "recipients", "cc", "bcc", "subject", "content", "sender_name", "recipient_names", "cc_names", "bcc_names"],- "query": "(test | test@*)"+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "simple_query_string": {+ "default_operator": "AND",+ "fields": ["sender", "reply_to", "recipients", "cc", "bcc"],+ "query": "(test | test@*)"+ }+ },+ {+ "simple_query_string": {+ "default_operator": "AND",+ "fields": ["subject", "content", "sender_name", "recipient_names", "cc_names", "bcc_names"],+ "query": "test*"+ }+ }+ ]}}]