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): multi-term AND with quoted-phrase support for channel messages (#3489)

gbirman576ba759323f
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rs
index ae9b34444b..2e2b37e315 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs
@@ -3,7 +3,7 @@ use std::borrow::Cow;
use crate::Result;
use crate::error::OpensearchClientError;
use crate::search::query::QueryKey;
-use crate::search::query::generate_terms_must_query;
+use crate::search::query::{TermCombine, generate_terms_must_query};
use models_opensearch::OpenSearchEntityType;
use opensearch_query_builder::{
BoolQueryBuilder, FieldSort, QueryType, Script, ScriptSort, ScriptSortType, SortOrder, SortType,
@@ -123,6 +123,8 @@ pub struct SearchQueryBuilder<T: SearchQueryConfig> {
pub ids_only: bool,
/// The ids to search for defaults to an empty vector
pub ids: Vec<String>,
+ /// How multi-term content queries combine.
+ pub term_combine: TermCombine,
_phantom: std::marker::PhantomData<T>,
}
@@ -137,10 +139,16 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
collapse: false,
ids_only: false,
ids: Vec::new(),
+ term_combine: TermCombine::default(),
_phantom: std::marker::PhantomData,
}
}
+ pub fn term_combine(mut self, term_combine: TermCombine) -> Self {
+ self.term_combine = term_combine;
+ self
+ }
+
pub fn match_type(mut self, match_type: &str) -> Self {
self.match_type = match_type.to_string();
self
@@ -258,7 +266,12 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
let terms: Cow<'_, [&str]> =
Cow::Owned(self.terms.iter().map(|t| t.as_str()).collect::<Vec<&str>>());
- let must_array = vec![generate_terms_must_query(query_key, T::CONTENT_KEY, terms)];
+ let must_array = vec![generate_terms_must_query(
+ query_key,
+ T::CONTENT_KEY,
+ terms,
+ self.term_combine,
+ )];
Ok(must_array)
}
@@ -273,7 +286,12 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
let terms: Cow<'_, [&str]> =
Cow::Owned(self.terms.iter().map(|t| t.as_str()).collect::<Vec<&str>>());
- Ok(generate_terms_must_query(query_key, T::TITLE_KEY, terms))
+ Ok(generate_terms_must_query(
+ query_key,
+ T::TITLE_KEY,
+ terms,
+ self.term_combine,
+ ))
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
index 584d35beb8..c31c79102b 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
@@ -253,8 +253,7 @@ fn test_build_must_term_query_multiple_terms() -> anyhow::Result<()> {
let expected = serde_json::json!({
"bool": {
- "minimum_should_match": 1,
- "should": [
+ "must": [
{
"match_phrase": {
"content": "test1"
diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rs
index 3099d3083f..eb6f7ffd84 100644
--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs
@@ -9,7 +9,7 @@ use crate::{
DefaultSearchResponse, Hit, MacroEm, SearchGotoChannel, SearchGotoContent, SearchHit,
exclude_source_content, inject_fragment_size, parse_highlight_hit,
},
- query::Keys,
+ query::{Keys, TermCombine},
},
};
@@ -53,7 +53,9 @@ pub(crate) struct ChannelMessageQueryBuilder {
impl ChannelMessageQueryBuilder {
pub fn new(terms: Vec<String>) -> Self {
Self {
- inner: SearchQueryBuilder::new(terms),
+ // Channel messages are single-doc-per-message, so every term
+ // must match the same document.
+ inner: SearchQueryBuilder::new(terms).term_combine(TermCombine::And),
..Default::default()
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs b/rust/cloud-storage/opensearch_client/src/search/channels/test.rs
index ad7f3e8c64..558922086f 100644
--- a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/channels/test.rs
@@ -50,3 +50,55 @@ fn test_build_bool_query() -> anyhow::Result<()> {
Ok(())
}
+
+#[test]
+fn test_build_bool_query_multi_term_ands_inside_opensearch() -> anyhow::Result<()> {
+ // Two terms — each becomes its own `match_phrase` clause and they
+ // combine with `must` so both must appear in the same message.
+ // Quoted phrases like "foo bar" arrive here as a single token and use
+ // the same `match_phrase` path.
+ let builder = ChannelMessageQueryBuilder::new(vec!["foo".to_string(), "bar baz".to_string()])
+ .match_type("exact")
+ .user_id("user123")
+ .ids(vec!["id1".to_string()]);
+
+ let result = builder.build_bool_query()?;
+
+ let expected = serde_json::json!({
+ "bool": {
+ "must": [
+ {
+ "bool": {
+ "minimum_should_match": 1,
+ "should": [
+ {
+ "bool": {
+ "must": [
+ { "match_phrase": { "content": "foo" } },
+ { "match_phrase": { "content": "bar baz" } }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ],
+ "filter": [
+ {
+ "bool": {
+ "minimum_should_match": 1,
+ "should": [
+ { "terms": { "entity_id": ["id1"] } },
+ { "term": { "sender_id": "user123" } }
+ ]
+ }
+ },
+ { "term": { "_index": "channels" } }
+ ]
+ }
+ });
+
+ assert_eq!(result.build().to_json(), expected);
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/opensearch_client/src/search/query.rs b/rust/cloud-storage/opensearch_client/src/search/query.rs
index dc26fd085c..2228963168 100644
--- a/rust/cloud-storage/opensearch_client/src/search/query.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/query.rs
@@ -72,15 +72,23 @@ impl QueryKey {
}
}
-/// Generate the terms for the "must" query
+/// How multi-term content queries combine.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum TermCombine {
+ #[default]
+ And,
+}
+
+/// Generate the terms for the "must" query — each term becomes its own
+/// `match_*` clause and the clauses are combined per `combine`.
pub(crate) fn generate_terms_must_query<'a>(
query_key: QueryKey,
field: &'a str,
terms: impl Into<Cow<'a, [&'a str]>>,
+ combine: TermCombine,
) -> QueryType<'a> {
let terms = terms.into();
- // Map terms to queries
let queries: Vec<_> = terms
.iter()
.map(|term| {
@@ -96,16 +104,16 @@ pub(crate) fn generate_terms_must_query<'a>(
return queries[0].clone();
}
- // 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_should_query.should(query);
+ let mut bool_query = BoolQueryBuilder::new();
+ match combine {
+ TermCombine::And => {
+ for query in queries {
+ bool_query.must(query);
+ }
+ }
}
- terms_should_query.build().into()
+ bool_query.build().into()
}
#[cfg(test)]
diff --git a/rust/cloud-storage/opensearch_client/src/search/query/test.rs b/rust/cloud-storage/opensearch_client/src/search/query/test.rs
index 24b8f61efb..a1723c9755 100644
--- a/rust/cloud-storage/opensearch_client/src/search/query/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/query/test.rs
@@ -74,10 +74,10 @@ fn test_query_key_create_query_partial() -> anyhow::Result<()> {
}
#[test]
-fn test_generate_terms_must_query() -> anyhow::Result<()> {
+fn test_generate_terms_must_query_single_term() -> anyhow::Result<()> {
let terms: Cow<'_, [&str]> = Cow::Borrowed(&["test"]);
- let result = generate_terms_must_query(QueryKey::MatchPhrase, "test", terms);
+ let result = generate_terms_must_query(QueryKey::MatchPhrase, "test", terms, TermCombine::And);
let expected = serde_json::json!({
"match_phrase": {
@@ -87,29 +87,20 @@ fn test_generate_terms_must_query() -> anyhow::Result<()> {
assert_eq!(result.to_json(), expected);
- let terms: Cow<'_, [&str]> = Cow::Borrowed(&["test", "test2"]);
- let result = generate_terms_must_query(QueryKey::MatchPhrasePrefix, "test", terms);
+ Ok(())
+}
+
+#[test]
+fn test_generate_terms_must_query_and_combine() -> anyhow::Result<()> {
+ let terms: Cow<'_, [&str]> = Cow::Borrowed(&["foo", "bar"]);
+ let result =
+ generate_terms_must_query(QueryKey::MatchPhrase, "content", terms, TermCombine::And);
let expected = serde_json::json!({
"bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "match_phrase_prefix": {
- "test": {
- "query": "test",
- "max_expansions": 256
- }
- }
- },
- {
- "match_phrase_prefix": {
- "test": {
- "query": "test2",
- "max_expansions": 256
- }
- }
- }
+ "must": [
+ { "match_phrase": { "content": "foo" } },
+ { "match_phrase": { "content": "bar" } }
]
}
});
diff --git a/rust/cloud-storage/search_service/src/api/search/channel.rs b/rust/cloud-storage/search_service/src/api/search/channel.rs
index de940db5ca..029b2371d7 100644
--- a/rust/cloud-storage/search_service/src/api/search/channel.rs
+++ b/rust/cloud-storage/search_service/src/api/search/channel.rs
@@ -1,4 +1,5 @@
use crate::api::search::simple::SearchError;
+use crate::api::search::terms::split_search_terms;
use chrono::{DateTime, Utc};
use indexmap::IndexMap;
use std::collections::HashMap;
@@ -206,11 +207,18 @@ pub async fn handler(
return Err(SearchError::InvalidPageSize);
}
- let terms = match (req.query, req.terms) {
+ let raw_terms = match (req.query, req.terms) {
(Some(q), _) if !q.trim().is_empty() => vec![q.trim().to_string()],
(_, Some(t)) if !t.is_empty() => t,
_ => return Err(SearchError::NoQueryOrTermsProvided),
};
+ // Whitespace-split outside double quotes so `foo bar` matches messages
+ // containing both words (ANDed inside OpenSearch) while `"foo bar"`
+ // stays an exact-phrase term.
+ let terms = split_search_terms(&raw_terms);
+ if terms.is_empty() {
+ return Err(SearchError::NoQueryOrTermsProvided);
+ }
if terms.iter().any(|t| t.len() < 3) {
return Err(SearchError::InvalidQuerySize);
}
diff --git a/rust/cloud-storage/search_service/src/api/search/mod.rs b/rust/cloud-storage/search_service/src/api/search/mod.rs
index 13d48ed675..bdeba1eb5a 100644
--- a/rust/cloud-storage/search_service/src/api/search/mod.rs
+++ b/rust/cloud-storage/search_service/src/api/search/mod.rs
@@ -10,6 +10,7 @@ pub(in crate::api) mod email;
pub(in crate::api::search) mod enrich;
pub(in crate::api) mod project;
pub mod simple;
+pub(in crate::api::search) mod terms;
pub mod unified;
pub fn router() -> Router<SearchHandlerState> {
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 ef3510b142..424c573327 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
@@ -76,34 +76,7 @@ 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
-}
+use crate::api::search::terms::split_search_terms;
/// Creates a unified search request and performs the search
/// by calling individual simple search endpoints for each entity type
@@ -224,20 +197,20 @@ pub(in crate::api::search) async fn perform_unified_search(
// Set terms on each index's search args.
//
- // Emails always get whitespace-split terms (each term matched
- // independently across many fields, ANDed inside OpenSearch).
- // Documents get split terms only once the alias points at a
- // join-shape index, where each term becomes a separate has_child
- // clause ANDed via bool.must. While the alias still points at the
- // flat-shape index, the documents branch keeps the single adjacent
- // phrase-prefix behavior.
+ // Emails and channels both get 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 get split terms
+ // once the 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 channel_terms = split_search_terms(&terms);
filter_document_response.terms = document_terms;
- filter_channel_response.terms = terms.clone();
+ filter_channel_response.terms = channel_terms;
filter_chat_response.terms = terms.clone();
filter_email_response.terms = email_terms.clone();
filter_call_record_response.terms = terms.clone();
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 4e9c1e9af6..a8c02f5d83 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,67 +4,6 @@ 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/terms.rs b/rust/cloud-storage/search_service/src/api/search/terms.rs
new file mode 100644
index 0000000000..6277cda77d
--- /dev/null
+++ b/rust/cloud-storage/search_service/src/api/search/terms.rs
@@ -0,0 +1,38 @@
+//! Shared search-term parsing.
+//!
+//! [`split_search_terms`] tokenizes user input by whitespace while preserving
+//! double-quoted phrases so callers can build AND-of-terms queries where each
+//! quoted span counts as a single phrase term. Used by both the unified
+//! dispatch and the channel-only endpoint.
+
+/// Splits search terms by whitespace, preserving double-quoted phrases.
+/// e.g. `["hello world"]` → `["hello", "world"]`
+/// e.g. `[r#""hello world" test"#]` → `["hello world", "test"]`
+pub(in crate::api::search) 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
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/search_service/src/api/search/terms/test.rs b/rust/cloud-storage/search_service/src/api/search/terms/test.rs
new file mode 100644
index 0000000000..cb877a2609
--- /dev/null
+++ b/rust/cloud-storage/search_service/src/api/search/terms/test.rs
@@ -0,0 +1,60 @@
+use super::*;
+
+#[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"]
+ );
+}