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.

Remove PG email search, use OpenSearch for all email queries (#2585)

gbirman239e9e48c05b
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index c0456177f6..59b75813e5 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -9471,7 +9471,6 @@ dependencies = [
"chrono",
"comms_db_client",
"document_sub_type",
- "email_contact_search",
"email_db_client",
"futures",
"http-body-util",
diff --git a/rust/cloud-storage/models_search_cursor/src/lib.rs b/rust/cloud-storage/models_search_cursor/src/lib.rs
index b5ff404e4a..e81bc9ac0a 100644
--- a/rust/cloud-storage/models_search_cursor/src/lib.rs
+++ b/rust/cloud-storage/models_search_cursor/src/lib.rs
@@ -95,10 +95,6 @@ pub struct SearchCursor {
pub chat_name_cursor: SearchCursorOption,
/// The content cursor
pub content_cursor: SearchCursorOption,
- /// The email subject cursor
- pub email_subject_cursor: SearchCursorOption,
- /// The email contact cursor
- pub email_contact_cursor: SearchCursorOption,
/// The project cursor
pub project_name_cursor: SearchCursorOption,
}
@@ -124,8 +120,6 @@ impl SearchCursor {
self.document_name_cursor.is_done()
&& self.chat_name_cursor.is_done()
&& self.content_cursor.is_done()
- && self.email_subject_cursor.is_done()
- && self.email_contact_cursor.is_done()
&& self.project_name_cursor.is_done()
}
}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-0e403c8b2157afd77299829b8cdf94755523a26b5434b639bb8e42ecfa0441f2.json b/rust/cloud-storage/name_search/.sqlx/query-0e403c8b2157afd77299829b8cdf94755523a26b5434b639bb8e42ecfa0441f2.json
deleted file mode 100644
index 607c6d8d85..0000000000
--- a/rust/cloud-storage/name_search/.sqlx/query-0e403c8b2157afd77299829b8cdf94755523a26b5434b639bb8e42ecfa0441f2.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE thread_id = ANY($1)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\",\n regexp_replace(\n om.subject,\n $6,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n t.latest_non_spam_message_ts as updated_at\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE om.subject ILIKE $2\n AND (\n $4::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)\n )\n AND (\n $7::bool IS NULL\n OR $7::bool = (NOT (\n EXISTS (\n SELECT 1 FROM email_messages em_dep\n JOIN email_message_labels ml_dep ON ml_dep.message_id = em_dep.id\n JOIN email_labels l_dep ON ml_dep.label_id = l_dep.id\n WHERE em_dep.thread_id = t.id\n AND l_dep.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')\n )\n AND NOT EXISTS (\n SELECT 1 FROM email_messages em_pri\n JOIN email_message_labels ml_pri ON ml_pri.message_id = em_pri.id\n JOIN email_labels l_pri ON ml_pri.label_id = l_pri.id\n WHERE em_pri.thread_id = t.id\n AND l_pri.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')\n )\n ))\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $3\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "entity_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name!",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "name_highlighted",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "updated_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "UuidArray",
- "Text",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text",
- "Bool"
- ]
- },
- "nullable": [
- false,
- true,
- null,
- true
- ]
- },
- "hash": "0e403c8b2157afd77299829b8cdf94755523a26b5434b639bb8e42ecfa0441f2"
-}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-2a2aeff74152cf2eaec9f76d9d6793697687c7ec622074bed484fd62fbd8fd57.json b/rust/cloud-storage/name_search/.sqlx/query-2a2aeff74152cf2eaec9f76d9d6793697687c7ec622074bed484fd62fbd8fd57.json
deleted file mode 100644
index 03dfa800fe..0000000000
--- a/rust/cloud-storage/name_search/.sqlx/query-2a2aeff74152cf2eaec9f76d9d6793697687c7ec622074bed484fd62fbd8fd57.json
+++ /dev/null
@@ -1,48 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH user_link_ids AS (\n SELECT id FROM email_links WHERE macro_id = $1\n ),\n matching_threads AS (\n SELECT DISTINCT thread_id\n FROM email_messages em\n WHERE em.link_id IN (SELECT id FROM user_link_ids)\n AND (thread_id = ANY($2) OR $3)\n AND em.subject ILIKE $4\n ),\n oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE thread_id IN (SELECT thread_id FROM matching_threads)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\",\n regexp_replace(\n om.subject,\n $8,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n t.latest_non_spam_message_ts as updated_at\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE t.link_id IN (SELECT id FROM user_link_ids)\n AND (\n $6::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($6, $7)\n )\n AND (\n $9::bool IS NULL\n OR $9::bool = (NOT (\n EXISTS (\n SELECT 1 FROM email_messages em_dep\n JOIN email_message_labels ml_dep ON ml_dep.message_id = em_dep.id\n JOIN email_labels l_dep ON ml_dep.label_id = l_dep.id\n WHERE em_dep.thread_id = t.id\n AND l_dep.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')\n )\n AND NOT EXISTS (\n SELECT 1 FROM email_messages em_pri\n JOIN email_message_labels ml_pri ON ml_pri.message_id = em_pri.id\n JOIN email_labels l_pri ON ml_pri.label_id = l_pri.id\n WHERE em_pri.thread_id = t.id\n AND l_pri.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')\n )\n ))\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $5\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "entity_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name!",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "name_highlighted",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "updated_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "UuidArray",
- "Bool",
- "Text",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text",
- "Bool"
- ]
- },
- "nullable": [
- false,
- true,
- null,
- true
- ]
- },
- "hash": "2a2aeff74152cf2eaec9f76d9d6793697687c7ec622074bed484fd62fbd8fd57"
-}
diff --git a/rust/cloud-storage/name_search/fixtures/email.sql b/rust/cloud-storage/name_search/fixtures/email.sql
deleted file mode 100644
index 7bbfdefbdd..0000000000
--- a/rust/cloud-storage/name_search/fixtures/email.sql
+++ /dev/null
@@ -1,131 +0,0 @@
--- Test macro_users
-INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
-VALUES
- ('a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_user1'),
- ('a2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'stripe_user2'),
- ('a3333333-3333-3333-3333-333333333333', '[email protected]', '[email protected]', 'stripe_user3');
-
--- Test users
-INSERT INTO "User" (id, email, name, macro_user_id)
-VALUES
- ('macro|[email protected]', '[email protected]', 'Test User 1', 'a1111111-1111-1111-1111-111111111111'),
- ('macro|[email protected]', '[email protected]', 'Test User 2', 'a2222222-2222-2222-2222-222222222222'),
- ('macro|[email protected]', '[email protected]', 'Test User 3', 'a3333333-3333-3333-3333-333333333333');
-
--- Email links (email account connections for each user)
-INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
-VALUES
- ('00000000-0000-0001-0000-000000000001', 'macro|[email protected]', 'fa_user1', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
- ('00000000-0000-0002-0000-000000000002', 'macro|[email protected]', 'fa_user2', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
- ('00000000-0000-0003-0000-000000000003', 'macro|[email protected]', 'fa_user3', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');
-
--- Email contacts (senders/recipients)
-INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
-VALUES
- -- Contacts for user1's link
- ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Sender One', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
- ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Sender Two', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
-
- -- Contacts for user2's link
- ('cccccccc-cccc-cccc-cccc-cccccccccccc', '00000000-0000-0002-0000-000000000002', '[email protected]', 'Sender Three', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
-
- -- Contacts for user3's link
- ('dddddddd-dddd-dddd-dddd-dddddddddddd', '00000000-0000-0003-0000-000000000003', '[email protected]', 'Sender Four', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');
-
--- Email threads for user1
--- Threads matching "invoice" (3 threads)
-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
-VALUES
- -- Thread 1: Invoice from Q1 2024 (oldest invoice, latest_non_spam_message_ts: 2024-12-01)
- ('11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-01 10:00:00+00', '2024-01-01 10:00:00+00', '2024-12-01 10:00:00+00'),
-
- -- Thread 2: Monthly Invoice - December (multiple messages, latest_non_spam_message_ts: 2024-12-02)
- ('22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-02 10:00:00+00', '2024-02-01 10:00:00+00', '2024-12-02 10:00:00+00'),
-
- -- Thread 3: IMPORTANT: INVOICE DUE (uppercase, latest_non_spam_message_ts: 2024-12-06)
- ('66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-06 10:00:00+00', '2024-06-01 10:00:00+00', '2024-12-06 10:00:00+00');
-
--- Threads matching "meet" (2 threads)
-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
-VALUES
- -- Thread 4: Team Meeting Notes (latest_non_spam_message_ts: 2024-12-03)
- ('33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-03 10:00:00+00', '2024-03-01 10:00:00+00', '2024-12-03 10:00:00+00'),
-
- -- Thread 5: Fwd: Client Meeting Tomorrow (latest_non_spam_message_ts: 2024-12-04)
- ('44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-04 10:00:00+00', '2024-04-01 10:00:00+00', '2024-12-04 10:00:00+00');
-
--- Other threads for user1 (for various test scenarios)
-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
-VALUES
- -- Thread 6: Weekly Update (no match, latest_non_spam_message_ts: 2024-12-05)
- ('55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-05 10:00:00+00', '2024-05-01 10:00:00+00', '2024-12-05 10:00:00+00'),
-
- -- Thread 7: Project Status (no match, latest_non_spam_message_ts: 2024-12-07)
- ('77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-07 10:00:00+00', '2024-07-01 10:00:00+00', '2024-12-07 10:00:00+00');
-
--- Email threads for user2 (for isolation testing)
-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
-VALUES
- ('88888888-8888-8888-8888-888888888888', '00000000-0000-0002-0000-000000000002', true, false, '2024-12-08 10:00:00+00', '2024-08-01 10:00:00+00', '2024-12-08 10:00:00+00');
-
--- Email threads for user3 (for shared thread testing)
-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
-VALUES
- ('99999999-9999-9999-9999-999999999999', '00000000-0000-0003-0000-000000000003', true, false, '2024-12-09 10:00:00+00', '2024-09-01 10:00:00+00', '2024-12-09 10:00:00+00');
-
--- Email messages for user1's threads
--- Thread 11111111: Invoice from Q1 2024 (multiple messages, oldest has the search subject)
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- -- Oldest message (this is what gets searched)
- ('10000000-0001-0000-0000-000000000001', '11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Invoice from Q1 2024', '2024-01-01 10:00:00+00', false, false, '2024-01-01 10:00:00+00', '2024-01-01 10:00:00+00'),
-
- -- Newer reply (should not be used for search)
- ('10000000-0001-0000-0000-000000000002', '11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Re: Invoice from Q1 2024', '2024-12-01 10:00:00+00', false, true, '2024-12-01 10:00:00+00', '2024-12-01 10:00:00+00');
-
--- Thread 22222222: Monthly Invoice - December (3 messages to test oldest message logic)
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- -- Oldest message with "Monthly Invoice" (this is what gets searched)
- ('10000000-0002-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Re: Monthly Invoice - December', '2024-02-01 10:00:00+00', false, false, '2024-02-01 10:00:00+00', '2024-02-01 10:00:00+00'),
-
- -- Middle message (should not be used for search)
- ('10000000-0002-0000-0000-000000000002', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Re: Re: Monthly Invoice - December', '2024-02-02 10:00:00+00', false, true, '2024-02-02 10:00:00+00', '2024-02-02 10:00:00+00'),
-
- -- Newest message with different subject (should not be used for search)
- ('10000000-0002-0000-0000-000000000003', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Re: Re: Re: Payment Processed', '2024-12-02 10:00:00+00', false, false, '2024-12-02 10:00:00+00', '2024-12-02 10:00:00+00');
-
--- Thread 33333333: Team Meeting Notes
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- ('10000000-0003-0000-0000-000000000001', '33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Team Meeting Notes', '2024-03-01 10:00:00+00', false, false, '2024-03-01 10:00:00+00', '2024-03-01 10:00:00+00');
-
--- Thread 44444444: Fwd: Client Meeting Tomorrow
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- ('10000000-0004-0000-0000-000000000001', '44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Fwd: Client Meeting Tomorrow', '2024-04-01 10:00:00+00', false, false, '2024-04-01 10:00:00+00', '2024-04-01 10:00:00+00');
-
--- Thread 55555555: Weekly Update
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- ('10000000-0005-0000-0000-000000000001', '55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Weekly Update - January 2024', '2024-05-01 10:00:00+00', false, false, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00');
-
--- Thread 66666666: IMPORTANT: INVOICE DUE (uppercase invoice)
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- ('10000000-0006-0000-0000-000000000001', '66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'IMPORTANT: INVOICE DUE', '2024-06-01 10:00:00+00', false, false, '2024-06-01 10:00:00+00', '2024-06-01 10:00:00+00');
-
--- Thread 77777777: Project Status
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- ('10000000-0007-0000-0000-000000000001', '77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Project Status Report', '2024-07-01 10:00:00+00', false, false, '2024-07-01 10:00:00+00', '2024-07-01 10:00:00+00');
-
--- Email messages for user2's threads (for isolation testing)
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- ('10000000-0008-0000-0000-000000000001', '88888888-8888-8888-8888-888888888888', '00000000-0000-0002-0000-000000000002', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'User2 Private Email', '2024-08-01 10:00:00+00', false, false, '2024-08-01 10:00:00+00', '2024-08-01 10:00:00+00');
-
--- Email messages for user3's threads (for shared thread testing)
-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
-VALUES
- ('10000000-0009-0000-0000-000000000001', '99999999-9999-9999-9999-999999999999', '00000000-0000-0003-0000-000000000003', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'User3 Invoice Shared', '2024-09-01 10:00:00+00', false, false, '2024-09-01 10:00:00+00', '2024-09-01 10:00:00+00');
diff --git a/rust/cloud-storage/name_search/src/email.rs b/rust/cloud-storage/name_search/src/email.rs
deleted file mode 100644
index 27234431bb..0000000000
--- a/rust/cloud-storage/name_search/src/email.rs
+++ /dev/null
@@ -1,271 +0,0 @@
-//! This module contains logic for searching email threads by oldest message subject
-#[cfg(not(test))]
-use cached::proc_macro::cached;
-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
-use models_search_cursor::{SearchCursorOption, SearchMethodCursor};
-use sqlx::{Pool, Postgres};
-use uuid::Uuid;
-
-use crate::{NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_regex};
-
-/// Searches email threads by IDs only
-async fn ids_search(
- db: &Pool<Postgres>,
- thread_ids: &[Uuid],
- search_pattern: String,
- highlight_pattern: String,
- limit: u32,
- cursor: Option<SearchMethodCursor>,
- importance: Option<bool>,
-) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {
- if thread_ids.is_empty() {
- return Err(NameSearchError::EmptyIdsWithIdsOnly);
- }
-
- let (cursor_updated_at, cursor_entity_id) = cursor
- .as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id)))
- .unwrap_or((None, None));
-
- // Fetch limit + 1 to determine if there are more results
- let fetch_limit = limit as i64 + 1;
-
- let rows = sqlx::query!(
- r#"
- WITH oldest_messages AS (
- SELECT DISTINCT ON (thread_id)
- thread_id,
- subject
- FROM email_messages
- WHERE thread_id = ANY($1)
- ORDER BY thread_id, internal_date_ts ASC
- )
- SELECT
- t.id as entity_id,
- om.subject as "name!",
- regexp_replace(
- om.subject,
- $6,
- '<macro_em>\1</macro_em>',
- 'gi'
- ) as name_highlighted,
- t.latest_non_spam_message_ts as updated_at
- FROM email_threads t
- INNER JOIN oldest_messages om ON om.thread_id = t.id
- WHERE om.subject ILIKE $2
- AND (
- $4::timestamptz IS NULL
- OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)
- )
- AND (
- $7::bool IS NULL
- OR $7::bool = (NOT (
- EXISTS (
- SELECT 1 FROM email_messages em_dep
- JOIN email_message_labels ml_dep ON ml_dep.message_id = em_dep.id
- JOIN email_labels l_dep ON ml_dep.label_id = l_dep.id
- WHERE em_dep.thread_id = t.id
- AND l_dep.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
- )
- AND NOT EXISTS (
- SELECT 1 FROM email_messages em_pri
- JOIN email_message_labels ml_pri ON ml_pri.message_id = em_pri.id
- JOIN email_labels l_pri ON ml_pri.label_id = l_pri.id
- WHERE em_pri.thread_id = t.id
- AND l_pri.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
- )
- ))
- )
- ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC
- LIMIT $3
- "#,
- thread_ids,
- search_pattern,
- fetch_limit,
- cursor_updated_at,
- cursor_entity_id,
- highlight_pattern,
- importance,
- )
- .fetch_all(db)
- .await
- .map_err(NameSearchError::DatabaseError)?;
-
- let results: Vec<NameSearchResult> = rows
- .into_iter()
- .filter_map(|row| {
- row.updated_at.map(|updated_at| NameSearchResult {
- entity_id: row.entity_id,
- entity_type: SearchEntityType::Emails,
- name: row.name_highlighted.unwrap_or(row.name),
- updated_at,
- })
- })
- .collect();
-
- Ok(SearchCursorOption::paginate(results, limit as usize))
-}
-
-/// Searches email threads by owner or IDs
-async fn owner_search<'a>(
- db: &Pool<Postgres>,
- macro_user_id: &MacroUserId<Lowercase<'a>>,
- thread_ids: &[Uuid],
- search_pattern: String,
- highlight_pattern: String,
- limit: u32,
- cursor: Option<SearchMethodCursor>,
- importance: Option<bool>,
-) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {
- let (cursor_updated_at, cursor_entity_id) = cursor
- .as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id)))
- .unwrap_or((None, None));
-
- // Fetch limit + 1 to determine if there are more results
- let fetch_limit = limit as i64 + 1;
-
- let rows = sqlx::query!(
- r#"
- WITH user_link_ids AS (
- SELECT id FROM email_links WHERE macro_id = $1
- ),
- matching_threads AS (
- SELECT DISTINCT thread_id
- FROM email_messages em
- WHERE em.link_id IN (SELECT id FROM user_link_ids)
- AND (thread_id = ANY($2) OR $3)
- AND em.subject ILIKE $4
- ),
- oldest_messages AS (
- SELECT DISTINCT ON (thread_id)
- thread_id,
- subject
- FROM email_messages
- WHERE thread_id IN (SELECT thread_id FROM matching_threads)
- ORDER BY thread_id, internal_date_ts ASC
- )
- SELECT
- t.id as entity_id,
- om.subject as "name!",
- regexp_replace(
- om.subject,
- $8,
- '<macro_em>\1</macro_em>',
- 'gi'
- ) as name_highlighted,
- t.latest_non_spam_message_ts as updated_at
- FROM email_threads t
- INNER JOIN oldest_messages om ON om.thread_id = t.id
- WHERE t.link_id IN (SELECT id FROM user_link_ids)
- AND (
- $6::timestamptz IS NULL
- OR (t.latest_non_spam_message_ts, t.id) < ($6, $7)
- )
- AND (
- $9::bool IS NULL
- OR $9::bool = (NOT (
- EXISTS (
- SELECT 1 FROM email_messages em_dep
- JOIN email_message_labels ml_dep ON ml_dep.message_id = em_dep.id
- JOIN email_labels l_dep ON ml_dep.label_id = l_dep.id
- WHERE em_dep.thread_id = t.id
- AND l_dep.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
- )
- AND NOT EXISTS (
- SELECT 1 FROM email_messages em_pri
- JOIN email_message_labels ml_pri ON ml_pri.message_id = em_pri.id
- JOIN email_labels l_pri ON ml_pri.label_id = l_pri.id
- WHERE em_pri.thread_id = t.id
- AND l_pri.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
- )
- ))
- )
- ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC
- LIMIT $5
- "#,
- macro_user_id.as_ref(),
- &thread_ids,
- thread_ids.is_empty(), // If empty, don't filter by thread_ids
- search_pattern,
- fetch_limit,
- cursor_updated_at,
- cursor_entity_id,
- highlight_pattern,
- importance,
- )
- .fetch_all(db)
- .await
- .map_err(NameSearchError::DatabaseError)?;
-
- let results: Vec<NameSearchResult> = rows
- .into_iter()
- .filter_map(|row| {
- row.updated_at.map(|updated_at| NameSearchResult {
- entity_id: row.entity_id,
- entity_type: SearchEntityType::Emails,
- name: row.name_highlighted.unwrap_or(row.name),
- updated_at,
- })
- })
- .collect();
-
- Ok(SearchCursorOption::paginate(results, limit as usize))
-}
-
-/// Searches over email threads by the subject of the oldest message in each thread
-#[tracing::instrument(skip(db), err)]
-#[cfg_attr(
- not(test),
- cached(
- time = 30,
- result = true,
- key = "String",
- convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}-{:?}", macro_user_id.as_ref(), thread_ids, term, ids_only, limit, cursor.as_ref().map(|c| format!("{}-{}", c.entity_id, c.updated_at)).unwrap_or_default(), importance) }"#
- )
-)]
-pub async fn search_email_subjects<'a>(
- db: &Pool<Postgres>,
- macro_user_id: &MacroUserId<Lowercase<'a>>,
- thread_ids: &[Uuid],
- term: String,
- ids_only: bool,
- limit: u32,
- cursor: Option<SearchMethodCursor>,
- importance: Option<bool>,
-) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {
- if term.is_empty() {
- return Err(NameSearchError::EmptySearchTerm);
- }
-
- let search_pattern = format!("%{term}%");
- let highlight_pattern = format!("({})", escape_regex(&term));
-
- if ids_only {
- ids_search(
- db,
- thread_ids,
- search_pattern,
- highlight_pattern,
- limit,
- cursor,
- importance,
- )
- .await
- } else {
- owner_search(
- db,
- macro_user_id,
- thread_ids,
- search_pattern,
- highlight_pattern,
- limit,
- cursor,
- importance,
- )
- .await
- }
-}
-
-#[cfg(test)]
-mod test;
diff --git a/rust/cloud-storage/name_search/src/email/test.rs b/rust/cloud-storage/name_search/src/email/test.rs
deleted file mode 100644
index 1c1fdedfaa..0000000000
--- a/rust/cloud-storage/name_search/src/email/test.rs
+++ /dev/null
@@ -1,586 +0,0 @@
-//! Tests for email module
-
-use macro_db_migrator::MACRO_DB_MIGRATIONS;
-use models_search_cursor::SearchCursorOption;
-use sqlx::{Pool, Postgres};
-use uuid::Uuid;
-
-use super::*;
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_empty_term(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- let result =
- search_email_subjects(&pool, &user_id, &[], "".to_string(), false, 10, None, None).await;
-
- assert!(result.is_err());
- assert!(matches!(
- result.unwrap_err(),
- NameSearchError::EmptySearchTerm
- ));
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_ids_only_with_empty_ids(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- let result = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "invoice".to_string(),
- true,
- 10,
- None,
- None,
- )
- .await;
-
- assert!(result.is_err());
- assert!(matches!(
- result.unwrap_err(),
- NameSearchError::EmptyIdsWithIdsOnly
- ));
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_ids_only_mode(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Search for "invoice" within specific thread IDs
- let thread_ids = vec![
- Uuid::parse_str("11111111-1111-1111-1111-111111111111")?, // Invoice from Q1 2024
- Uuid::parse_str("22222222-2222-2222-2222-222222222222")?, // Monthly Invoice
- Uuid::parse_str("55555555-5555-5555-5555-555555555555")?, // Weekly Update - won't match
- ];
-
- let response = search_email_subjects(
- &pool,
- &user_id,
- &thread_ids,
- "invoice".to_string(),
- true,
- 10,
- None,
- None,
- )
- .await?;
-
- // Should only return the 2 threads that match "invoice" from the provided IDs
- assert_eq!(response.items.len(), 2);
-
- // Verify results contain expected threads (ordered by latest_non_spam_message_ts DESC)
- assert_eq!(
- response.items[0].entity_id.to_string(),
- "22222222-2222-2222-2222-222222222222"
- );
- assert_eq!(response.items[0].entity_type, SearchEntityType::Emails);
- assert_eq!(
- response.items[0].name,
- "Re: Monthly <macro_em>Invoice</macro_em> - December"
- );
-
- assert_eq!(
- response.items[1].entity_id.to_string(),
- "11111111-1111-1111-1111-111111111111"
- );
- assert_eq!(
- response.items[1].name,
- "<macro_em>Invoice</macro_em> from Q1 2024"
- );
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_normal_mode_owned_threads(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Search for "invoice" across all user1's email threads
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "invoice".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- // Should return 3 threads matching "invoice" (2 with "invoice" + 1 with "INVOICE")
- assert_eq!(response.items.len(), 3);
-
- // Verify ordering by latest_non_spam_message_ts DESC
- assert_eq!(
- response.items[0].entity_id.to_string(),
- "66666666-6666-6666-6666-666666666666"
- );
- assert_eq!(
- response.items[0].name,
- "IMPORTANT: <macro_em>INVOICE</macro_em> DUE"
- );
-
- assert_eq!(
- response.items[1].entity_id.to_string(),
- "22222222-2222-2222-2222-222222222222"
- );
- assert_eq!(
- response.items[1].name,
- "Re: Monthly <macro_em>Invoice</macro_em> - December"
- );
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Search with uppercase term should match both lowercase and uppercase subjects
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "INVOICE".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- assert_eq!(response.items.len(), 3);
-
- // Search with lowercase term should also match both
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "invoice".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- assert_eq!(response.items.len(), 3);
-
- // Search with mixed case
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "InVoIcE".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- assert_eq!(response.items.len(), 3);
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_with_shared_threads(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Try to access a thread from user3 by passing its ID
- // In normal mode, even when thread_ids are specified, only threads belonging to
- // the user's link_id are returned. User3's thread belongs to user3's link_id,
- // so it won't be accessible to user1.
- let user3_thread_id = vec![Uuid::parse_str("99999999-9999-9999-9999-999999999999")?];
-
- let response = search_email_subjects(
- &pool,
- &user_id,
- &user3_thread_id,
- "invoice".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- // Should return 0 results because user3's thread doesn't belong to user1's link_id
- // Email isolation is enforced via link_id, not just thread ownership
- assert_eq!(response.items.len(), 0);
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_pagination_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Search with limit of 2
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "invoice".to_string(),
- false,
- 2,
- None,
- None,
- )
- .await?;
-
- assert_eq!(response.items.len(), 2);
-
- // Should get the 2 most recently updated threads with "invoice"
- assert_eq!(
- response.items[0].entity_id.to_string(),
- "66666666-6666-6666-6666-666666666666"
- );
- assert_eq!(
- response.items[1].entity_id.to_string(),
- "22222222-2222-2222-2222-222222222222"
- );
-
- // Should have a next_cursor since there are more results
- assert!(response.cursor.has_more());
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_pagination_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // First page with limit of 2
- let first_response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "invoice".to_string(),
- false,
- 2,
- None,
- None,
- )
- .await?;
-
- assert_eq!(first_response.items.len(), 2);
- assert!(first_response.cursor.has_more());
-
- // Extract cursor for second page
- let cursor = match first_response.cursor {
- SearchCursorOption::NotDone(c) => c,
- SearchCursorOption::Done => panic!("Expected more results"),
- };
-
- // Second page using cursor
- let second_response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "invoice".to_string(),
- false,
- 2,
- cursor,
- None,
- )
- .await?;
-
- assert_eq!(second_response.items.len(), 1);
-
- // Should get the next thread (skipping the first 2)
- assert_eq!(
- second_response.items[0].entity_id.to_string(),
- "11111111-1111-1111-1111-111111111111"
- );
-
- // Should NOT have next_cursor since we've reached the end
- assert!(second_response.cursor.is_done());
-
- // Verify no overlap between pages
- let first_ids: Vec<String> = first_response
- .items
- .iter()
- .map(|r| r.entity_id.to_string())
- .collect();
- let second_ids: Vec<String> = second_response
- .items
- .iter()
- .map(|r| r.entity_id.to_string())
- .collect();
-
- for id in &first_ids {
- assert!(
- !second_ids.contains(id),
- "Found duplicate ID between pages: {}",
- id
- );
- }
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_no_results(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Search for a term that doesn't match any email subjects
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "nonexistent".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- assert_eq!(response.items.len(), 0);
- assert!(response.cursor.is_done());
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_partial_match(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Search for partial term "meet" should match "meeting"
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "meet".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- assert_eq!(response.items.len(), 2);
- assert_eq!(
- response.items[0].entity_id.to_string(),
- "44444444-4444-4444-4444-444444444444"
- );
- assert_eq!(
- response.items[0].name,
- "Fwd: Client <macro_em>Meet</macro_em>ing Tomorrow"
- );
-
- assert_eq!(
- response.items[1].entity_id.to_string(),
- "33333333-3333-3333-3333-333333333333"
- );
- assert_eq!(
- response.items[1].name,
- "Team <macro_em>Meet</macro_em>ing Notes"
- );
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_user_isolation(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Search for "User2" - user1 should not see user2's private email threads
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "User2".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- // Should return 0 results (user2's emails are not linked to user1)
- assert_eq!(response.items.len(), 0);
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_searches_oldest_message(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Thread 22222222 has 3 messages:
- // 1. Oldest (2024-02-01): "Re: Monthly Invoice - December"
- // 2. Middle (2024-02-02): "Re: Re: Monthly Invoice - December"
- // 3. Newest (2024-12-02): "Re: Re: Re: Payment Processed"
-
- // Searching for "Monthly Invoice" should find the thread because a message matches
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "Monthly Invoice".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- assert!(response.items.iter().any(|r| {
- r.entity_id
- .to_string()
- .eq("22222222-2222-2222-2222-222222222222")
- }));
-
- // Searching for "Payment Processed" should also find it because we search all messages in the thread
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "Payment Processed".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- assert!(response.items.iter().any(|r| {
- r.entity_id
- .to_string()
- .eq("22222222-2222-2222-2222-222222222222")
- }));
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("email"))
-)]
-async fn test_search_email_subjects_multiple_messages_per_thread(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")
- .map(|l| l.lowercase())
- .unwrap();
-
- // Thread 11111111 has multiple messages - should return thread only once with oldest subject
- let response = search_email_subjects(
- &pool,
- &user_id,
- &[],
- "invoice".to_string(),
- false,
- 10,
- None,
- None,
- )
- .await?;
-
- // Count how many times thread 11111111 appears (should be exactly once)
- let count = response
- .items
- .iter()
- .filter(|r| {
- r.entity_id
- .to_string()
- .eq("11111111-1111-1111-1111-111111111111")
- })
- .count();
- assert_eq!(count, 1);
-
- // Verify it returns the oldest message's subject
- let thread_result = response
- .items
- .iter()
- .find(|r| {
- r.entity_id
- .to_string()
- .eq("11111111-1111-1111-1111-111111111111")
- })
- .unwrap();
- assert_eq!(
- thread_result.name,
- "<macro_em>Invoice</macro_em> from Q1 2024"
- );
-
- Ok(())
-}
diff --git a/rust/cloud-storage/name_search/src/lib.rs b/rust/cloud-storage/name_search/src/lib.rs
index 9bc284584d..2610cf8d67 100644
--- a/rust/cloud-storage/name_search/src/lib.rs
+++ b/rust/cloud-storage/name_search/src/lib.rs
@@ -3,13 +3,10 @@
mod chat;
mod document;
-#[allow(clippy::too_many_arguments)]
-mod email;
mod project;
pub use chat::*;
pub use document::*;
-pub use email::*;
pub use models_opensearch::SearchEntityType;
use models_search_cursor::{PaginatedResult, SearchCursorAttributes};
pub use project::*;
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rs
index 51d8768da9..c29be6befc 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs
@@ -246,6 +246,19 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
Ok(must_array)
}
+
+ /// Builds a query targeting the title field (TITLE_KEY)
+ pub fn build_title_term_query<'a>(&'a self) -> Result<QueryType<'a>> {
+ if self.terms.is_empty() {
+ return Err(OpensearchClientError::NoTermsProvided);
+ }
+
+ let query_key = QueryKey::from_match_type(&self.match_type)?;
+ 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))
+ }
}
#[cfg(test)]
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rs
index 9c8a9d40cf..4e91c43fdf 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs
@@ -13,7 +13,7 @@ pub(crate) struct EmailSearchConfig;
impl SearchQueryConfig for EmailSearchConfig {
const USER_ID_KEY: &'static str = "user_id";
- const TITLE_KEY: &'static str = "name";
+ const TITLE_KEY: &'static str = "subject";
const ENTITY_INDEX: SearchEntityType = SearchEntityType::Emails;
}
@@ -72,6 +72,8 @@ pub(crate) struct EmailQueryBuilder {
/// ANDed together. Contradictory combinations (e.g. importance=true with
/// include_labels=["CATEGORY_PROMOTIONS"]) will return no results.
importance: Option<bool>,
+ /// When true, only search the subject field (for name-only search mode)
+ subject_only: bool,
}
impl EmailQueryBuilder {
@@ -86,6 +88,7 @@ impl EmailQueryBuilder {
include_labels: Vec::new(),
exclude_labels: Vec::new(),
importance: None,
+ subject_only: false,
}
}
@@ -140,12 +143,23 @@ impl EmailQueryBuilder {
self
}
+ pub fn subject_only(mut self, subject_only: bool) -> Self {
+ self.subject_only = subject_only;
+ self
+ }
+
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 {
+ // In subject_only mode (name search), replace with a match on TITLE_KEY (subject).
+ // Otherwise replace with simple_query_string across all email fields.
+ if self.subject_only {
+ let title_query = self.inner.build_title_term_query()?;
+ let mut inner = BoolQueryBuilder::new();
+ inner.minimum_should_match(1);
+ 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,
@@ -298,6 +312,7 @@ pub struct EmailSearchArgs {
pub match_type: String,
pub collapse: bool,
pub ids_only: bool,
+ pub subject_only: bool,
}
impl From<EmailSearchArgs> for EmailQueryBuilder {
@@ -318,6 +333,7 @@ impl From<EmailSearchArgs> for EmailQueryBuilder {
.importance(args.importance)
.collapse(args.collapse)
.ids_only(args.ids_only)
+ .subject_only(args.subject_only)
}
}
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 569fdc5637..f451ba68e1 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
@@ -50,6 +50,7 @@ fn test_email_search_args_build_injects_simple_query_string() -> anyhow::Result<
match_type: "partial".to_string(),
collapse: true,
ids_only: false,
+ subject_only: false,
}
.into();
@@ -137,11 +138,10 @@ fn test_build_bool_query() -> anyhow::Result<()> {
],
"must": [
{
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {"match_phrase": {"content": "test"}}
- ]
+ "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@*)"
}
}
]
diff --git a/rust/cloud-storage/opensearch_client/src/search/model/mod.rs b/rust/cloud-storage/opensearch_client/src/search/model/mod.rs
index 18d01dc879..ac06ea3435 100644
--- a/rust/cloud-storage/opensearch_client/src/search/model/mod.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/model/mod.rs
@@ -278,15 +278,25 @@ pub(crate) fn parse_highlight_hit(
.map(|v| v.iter().map(|f| normalize_highlight_fragment(f)).collect())
.unwrap_or_default(),
sender: highlight
- .get("sender")
+ .get("sender_name")
+ .or_else(|| highlight.get("sender"))
.and_then(|v| v.first())
.map(|v| v.to_string()),
recipients: highlight
- .get("recipients")
+ .get("recipient_names")
+ .or_else(|| highlight.get("recipients"))
+ .map(|v| v.to_vec())
+ .unwrap_or_default(),
+ cc: highlight
+ .get("cc_names")
+ .or_else(|| highlight.get("cc"))
+ .map(|v| v.to_vec())
+ .unwrap_or_default(),
+ bcc: highlight
+ .get("bcc_names")
+ .or_else(|| highlight.get("bcc"))
.map(|v| v.to_vec())
.unwrap_or_default(),
- cc: highlight.get("cc").map(|v| v.to_vec()).unwrap_or_default(),
- bcc: highlight.get("bcc").map(|v| v.to_vec()).unwrap_or_default(),
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index a9533730cd..cc24fe3b82 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -95,6 +95,7 @@ impl From<UnifiedSearchArgs> for EmailSearchArgs {
include_labels: args.email_search_args.include_labels,
exclude_labels: args.email_search_args.exclude_labels,
importance: args.email_search_args.importance,
+ subject_only: args.email_search_args.subject_only,
}
}
}
@@ -161,6 +162,7 @@ pub struct UnifiedEmailSearchArgs {
pub include_labels: Vec<String>,
pub exclude_labels: Vec<String>,
pub importance: Option<bool>,
+ pub subject_only: bool,
}
#[derive(Debug, Default, Clone)]
@@ -416,14 +418,24 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
search_request_builder.add_sort(sort);
}
- let highlight = Highlight::new().require_field_match(true).field(
- "content",
+ let em_field = || {
HighlightField::new()
.highlight_type("plain")
.pre_tags(vec![MacroEm::Open.to_string()])
.post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(1),
- );
+ };
+ let highlight = Highlight::new()
+ .require_field_match(true)
+ .field("content", em_field().number_of_fragments(1))
+ .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))
+ .field("recipients", em_field().number_of_fragments(0))
+ .field("recipient_names", em_field().number_of_fragments(0))
+ .field("cc", em_field().number_of_fragments(0))
+ .field("cc_names", em_field().number_of_fragments(0))
+ .field("bcc", em_field().number_of_fragments(0))
+ .field("bcc_names", em_field().number_of_fragments(0));
search_request_builder.highlight(highlight);
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 1008c16d4b..adb7406152 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -464,12 +464,16 @@ 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"
- }
+ "content": { "number_of_fragments": 1, "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" },
+ "recipients": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "recipient_names": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "cc": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "cc_names": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "bcc": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "bcc_names": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" }
},
"require_field_match": true
},
@@ -644,15 +648,10 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
],
"must": [
{
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
+ "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@*)"
}
}
]
@@ -863,12 +862,16 @@ 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"
- }
+ "content": { "number_of_fragments": 1, "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" },
+ "recipients": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "recipient_names": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "cc": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "cc_names": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "bcc": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" },
+ "bcc_names": { "number_of_fragments": 0, "post_tags": ["</macro_em>"], "pre_tags": ["<macro_em>"], "type": "plain" }
},
"require_field_match": true
},
diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.toml
index 2acf12dc1f..6890f0e339 100644
--- a/rust/cloud-storage/search_service/Cargo.toml
+++ b/rust/cloud-storage/search_service/Cargo.toml
@@ -20,7 +20,6 @@ axum = { workspace = true }
chrono = { workspace = true }
comms_db_client = { path = "../comms_db_client" }
document_sub_type = { path = "../document_sub_type" }
-email_contact_search = { path = "../email_contact_search" }
email_db_client = { path = "../email_db_client" }
futures = { workspace = true }
http-body-util = { workspace = true }
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs b/rust/cloud-storage/search_service/src/api/search/simple/mod.rs
index 5976c0209b..cf3e72fc2f 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/mod.rs
@@ -5,7 +5,6 @@ use axum::{
response::{IntoResponse, Response},
routing::post,
};
-use email_contact_search::EmailContactSearchError;
use model::response::ErrorResponse;
use name_search::NameSearchError;
use opensearch_client::error::OpensearchClientError;
@@ -14,7 +13,6 @@ pub(in crate::api) mod filter;
pub(in crate::api) mod simple_channel;
pub(in crate::api) mod simple_chat;
pub(in crate::api) mod simple_document;
-pub(in crate::api) mod simple_email;
pub(in crate::api) mod simple_project;
pub mod simple_unified;
@@ -48,9 +46,6 @@ pub enum SearchError {
/// Name search error occurred
#[error("unable to name search")]
NameSearch(#[from] NameSearchError),
- /// Email contact search error occurred
- #[error("unable to search email contacts")]
- EmailContactSearch(#[from] EmailContactSearchError),
/// Internal error occurred
#[error("internal error")]
InternalError(#[from] anyhow::Error),
@@ -64,10 +59,9 @@ impl IntoResponse for SearchError {
| SearchError::InvalidQuerySize
| SearchError::InvalidCursor
| SearchError::NoQueryOrTermsProvided => StatusCode::BAD_REQUEST,
- SearchError::Search(_)
- | SearchError::NameSearch(_)
- | SearchError::EmailContactSearch(_)
- | SearchError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ SearchError::Search(_) | SearchError::NameSearch(_) | SearchError::InternalError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
};
(
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs
deleted file mode 100644
index 1bb8e3b7d1..0000000000
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs
+++ /dev/null
@@ -1,151 +0,0 @@
-use crate::api::search::simple::SearchError;
-use email_contact_search::ContactType;
-use macro_user_id::user_id::MacroUserId;
-use models_opensearch::SearchEntityType;
-use opensearch_client::search::model::{Highlight, SearchGotoContent, SearchGotoEmail, SearchHit};
-use sqlx::{Pool, Postgres, types::Uuid};
-
-#[derive(Debug)]
-pub(in crate::api::search) struct FilterEmailResponse {
- pub thread_ids: Vec<String>,
- pub ids_only: bool,
- pub importance: Option<bool>,
-}
-
-/// Performs the name search over email subjects
-#[tracing::instrument(skip(db), err)]
-pub(in crate::api::search::simple) async fn search_names<'a>(
- db: &Pool<Postgres>,
- user_id: &MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,
- filter_email_response: &FilterEmailResponse,
- 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 thread_uuids = filter_email_response
- .thread_ids
- .iter()
- .map(|t| t.parse().unwrap())
- .collect::<Vec<Uuid>>();
-
- name_search::search_email_subjects(
- db,
- user_id,
- &thread_uuids,
- term,
- filter_email_response.ids_only,
- limit,
- inner_cursor,
- filter_email_response.importance,
- )
- .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)
- })
-}
-
-/// Performs the contact search over email contacts (sender, recipients, cc, bcc)
-#[tracing::instrument(skip(db), err)]
-pub(in crate::api::search::simple) async fn search_contacts<'a>(
- db: &Pool<Postgres>,
- user_id: MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,
- term: String,
- limit: u32,
- cursor: models_search_cursor::SearchCursorOption,
- importance: Option<bool>,
-) -> 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,
- };
-
- email_contact_search::search_email_contacts(db, user_id, term, limit, inner_cursor, importance)
- .await
- .map_err(SearchError::EmailContactSearch)
- .map(|response| {
- let hits = response
- .items
- .into_iter()
- .map(|contact| {
- // Build highlight based on contact type
- let highlight = match contact.contact_type {
- ContactType::From => Highlight {
- sender: contact.contact_name.or(Some(contact.contact_email.clone())),
- ..Default::default()
- },
- ContactType::To => Highlight {
- recipients: vec![
- contact
- .contact_name
- .unwrap_or_else(|| contact.contact_email.clone()),
- ],
- ..Default::default()
- },
- ContactType::Cc => Highlight {
- cc: vec![
- contact
- .contact_name
- .unwrap_or_else(|| contact.contact_email.clone()),
- ],
- ..Default::default()
- },
- ContactType::Bcc => Highlight {
- bcc: vec![
- contact
- .contact_name
- .unwrap_or_else(|| contact.contact_email.clone()),
- ],
- ..Default::default()
- },
- };
-
- SearchHit {
- entity_id: contact.thread_id,
- entity_type: SearchEntityType::Emails,
- score: None,
- highlight,
- goto: Some(SearchGotoContent::Emails(SearchGotoEmail {
- email_message_id: contact.message_id,
- bcc: vec![],
- cc: vec![],
- labels: vec![],
- sent_at: None,
- sender: contact.contact_email,
- recipients: vec![],
- })),
- updated_at: Some(contact.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 eba86beaaa..f2a2a25ecf 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,6 +1,6 @@
use crate::api::search::simple::filter::FilterVariantToSearchArgs;
-use crate::api::search::simple::{simple_chat, simple_document, simple_email, simple_project};
+use crate::api::search::simple::{simple_chat, simple_document, simple_project};
use crate::api::{
context::SearchHandlerState,
search::{SearchPaginationParams, simple::SearchError},
@@ -26,8 +26,6 @@ use opensearch_client::search::unified::UnifiedSearchArgs;
enum SearchSource {
DocumentName,
ChatName,
- EmailSubject,
- EmailContact,
ProjectName,
Content,
}
@@ -177,7 +175,6 @@ pub(in crate::api::search) async fn perform_unified_search(
let should_include_projects = search_filters.should_include_projects;
let should_include_emails = search_filters.should_include_emails;
let email_terms = split_search_terms(&terms);
- let is_email_multi_term = email_terms.len() > 1;
// Await all tasks in parallel
let (
@@ -240,14 +237,6 @@ pub(in crate::api::search) async fn perform_unified_search(
.as_ref()
.map(|c| c.chat_name_cursor.clone())
.unwrap_or_default();
- let email_cursor = cursor
- .as_ref()
- .map(|c| c.email_subject_cursor.clone())
- .unwrap_or_default();
- let email_contact_cursor = cursor
- .as_ref()
- .map(|c| c.email_contact_cursor.clone())
- .unwrap_or_default();
let project_cursor = cursor
.as_ref()
.map(|c| c.project_name_cursor.clone())
@@ -261,8 +250,6 @@ pub(in crate::api::search) async fn perform_unified_search(
// 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 email_cursor_for_search = email_cursor.clone();
- let email_contact_cursor_for_search = email_contact_cursor.clone();
let project_cursor_for_search = project_cursor.clone();
let content_cursor_for_search = content_cursor.clone();
@@ -305,14 +292,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,
- email_results,
- email_contact_results,
- project_results,
- content_results,
- ) = tokio::join!(
+ let (doc_name_results, chat_results, project_results, content_results) = tokio::join!(
async {
if should_include_documents {
match search_on {
@@ -359,54 +339,6 @@ pub(in crate::api::search) async fn perform_unified_search(
Ok((vec![], SearchCursorOption::Done))
}
},
- async {
- // 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(
- &ctx.db,
- &user_id,
- &simple_email::FilterEmailResponse {
- ids_only: false,
- thread_ids: filter_email_response.thread_ids,
- importance: filter_email_response.importance,
- },
- name_search_term.clone(),
- page_size,
- email_cursor_for_search,
- )
- .await
- }
- SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),
- }
- } else {
- Ok((vec![], SearchCursorOption::Done))
- }
- },
- async {
- // 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(
- &ctx.db,
- user_id.clone(),
- name_search_term.clone(),
- page_size,
- email_contact_cursor_for_search,
- filter_email_response.importance,
- )
- .await
- }
- SearchOn::Name | SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),
- }
- } else {
- Ok((vec![], SearchCursorOption::Done))
- }
- },
async {
if should_include_projects {
match search_on {
@@ -431,20 +363,20 @@ pub(in crate::api::search) async fn perform_unified_search(
}
},
async {
- // We only want to search over content if you are not searching name only
- match search_on {
- SearchOn::Content | SearchOn::NameContent => {
- if unified_search_args.search_indices.is_empty() {
- Ok((vec![], SearchCursorOption::Done))
- } else if let SearchCursorOption::Done = unified_search_args.cursor {
- Ok((vec![], SearchCursorOption::Done))
- } else {
- ctx.opensearch_client
- .search_unified(unified_search_args)
- .await
- }
- }
- SearchOn::Name => Ok((vec![], SearchCursorOption::Done)),
+ // For Name-only mode, only search emails via OpenSearch (subject field
+ // via simple_query_string). Other entity types use PG name searches above.
+ let mut args = unified_search_args;
+ if matches!(search_on, SearchOn::Name) {
+ args.search_indices
+ .retain(|i| *i == models_opensearch::SearchEntityType::Emails);
+ args.email_search_args.subject_only = true;
+ }
+ if args.search_indices.is_empty() {
+ Ok((vec![], SearchCursorOption::Done))
+ } else if let SearchCursorOption::Done = args.cursor {
+ Ok((vec![], SearchCursorOption::Done))
+ } else {
+ ctx.opensearch_client.search_unified(args).await
}
},
);
@@ -452,16 +384,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 (email_hits, email_next_cursor) = email_results?;
- let (email_contact_hits, email_contact_next_cursor) = email_contact_results?;
let (project_hits, project_next_cursor) = project_results?;
let (content_hits, content_next_cursor) = content_results?;
// Track original counts before combining
let doc_name_count = doc_hits.len();
let chat_name_count = chat_hits.len();
- let email_subject_count = email_hits.len();
- let email_contact_count = email_contact_hits.len();
let project_name_count = project_hits.len();
let content_count = content_hits.len();
@@ -470,8 +398,6 @@ pub(in crate::api::search) async fn perform_unified_search(
"combine_and_sort_results",
doc_name_count,
chat_name_count,
- email_subject_count,
- email_contact_count,
project_name_count,
content_count
)
@@ -487,14 +413,6 @@ pub(in crate::api::search) async fn perform_unified_search(
hit,
source: SearchSource::ChatName,
}));
- combined.extend(email_hits.into_iter().map(|hit| TaggedSearchHit {
- hit,
- source: SearchSource::EmailSubject,
- }));
- combined.extend(email_contact_hits.into_iter().map(|hit| TaggedSearchHit {
- hit,
- source: SearchSource::EmailContact,
- }));
combined.extend(project_hits.into_iter().map(|hit| TaggedSearchHit {
hit,
source: SearchSource::ProjectName,
@@ -541,14 +459,6 @@ pub(in crate::api::search) async fn perform_unified_search(
.iter()
.filter(|h| h.source == SearchSource::ChatName)
.count();
- let included_email_subjects = final_tagged
- .iter()
- .filter(|h| h.source == SearchSource::EmailSubject)
- .count();
- let included_email_contacts = final_tagged
- .iter()
- .filter(|h| h.source == SearchSource::EmailContact)
- .count();
let included_project_names = final_tagged
.iter()
.filter(|h| h.source == SearchSource::ProjectName)
@@ -575,22 +485,6 @@ pub(in crate::api::search) async fn perform_unified_search(
&chat_cursor,
);
- let new_email_cursor = compute_next_cursor(
- &email_next_cursor,
- included_email_subjects,
- email_subject_count,
- find_last_of_source(&final_tagged, SearchSource::EmailSubject),
- &email_cursor,
- );
-
- let new_email_contact_cursor = compute_next_cursor(
- &email_contact_next_cursor,
- included_email_contacts,
- email_contact_count,
- find_last_of_source(&final_tagged, SearchSource::EmailContact),
- &email_contact_cursor,
- );
-
let new_project_cursor = compute_next_cursor(
&project_next_cursor,
included_project_names,
@@ -610,8 +504,6 @@ 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()
- || new_email_cursor.has_more()
- || new_email_contact_cursor.has_more()
|| new_project_cursor.has_more()
|| new_content_cursor.has_more();
@@ -620,8 +512,6 @@ pub(in crate::api::search) async fn perform_unified_search(
document_name_cursor: new_doc_cursor,
chat_name_cursor: new_chat_cursor,
content_cursor: new_content_cursor,
- email_subject_cursor: new_email_cursor,
- email_contact_cursor: new_email_contact_cursor,
project_name_cursor: new_project_cursor,
};
cursor.encode()
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 ffd4b408a5..58eead8291 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
@@ -201,7 +201,7 @@ fn test_compute_next_cursor_all_included_search_done_returns_done() {
Some(&make_tagged_hit(
Uuid::new_v4(),
Some(ts(1000)),
- SearchSource::EmailSubject,
+ SearchSource::Content,
)),
&SearchCursorOption::NotDone(None),
);
@@ -215,7 +215,7 @@ fn test_compute_next_cursor_all_included_but_search_not_done_continues() {
// generate cursor from last included (search may have more pages)
let entity_id = Uuid::new_v4();
let timestamp = ts(1000);
- let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::EmailSubject);
+ let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::Content);
let result = compute_next_cursor(
&SearchCursorOption::NotDone(None), // search says not done (more exists)
@@ -285,7 +285,7 @@ fn test_find_last_of_source_returns_none_when_not_found() {
make_tagged_hit(Uuid::new_v4(), Some(ts(2000)), SearchSource::ChatName),
];
- let last_email = find_last_of_source(&results, SearchSource::EmailSubject);
+ let last_email = find_last_of_source(&results, SearchSource::Content);
assert!(last_email.is_none());
}
@@ -336,7 +336,7 @@ fn test_cursor_logic_pagination_scenario() {
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(Uuid::new_v4(), Some(ts(4000)), SearchSource::EmailSubject),
+ 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),
];