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
feat(search): handle name and unified search using names index (#345)
Will Hutchinson6cee24373bed
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 627ea51f4a..7118fa2f17 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5869,9 +5869,9 @@ dependencies = [[[package]]name = "opensearch_query_builder"-version = "0.2.1"+version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fad14f01f6fddacf5c28f40c08384e206f68ecb135e253b01bcb5fd3af531472"+checksum = "3f4d171bfc21961e61231a8b8f7b06d34befb4152627d1c6b591aadd621c4681"dependencies = ["serde","serde_json",@@ -7419,6 +7419,7 @@ dependencies = ["macro_middleware","model","models_email",+ "models_opensearch","models_search","opensearch_client","secretsmanager_client",diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9b4a72a38a9c07c192f92d6cf883dfb65e04ec3553e7b85a0d6f356f4ef55aa7.json b/rust/cloud-storage/macro_db_client/.sqlx/query-0c3bf4ab99e5ef1c2100c82611aeaf4fe7ffe5734a57567dfdfea1a78cfbb3ee.jsonsimilarity index 60%rename from rust/cloud-storage/macro_db_client/.sqlx/query-9b4a72a38a9c07c192f92d6cf883dfb65e04ec3553e7b85a0d6f356f4ef55aa7.jsonrename to rust/cloud-storage/macro_db_client/.sqlx/query-0c3bf4ab99e5ef1c2100c82611aeaf4fe7ffe5734a57567dfdfea1a78cfbb3ee.jsonindex 9461a43d4a..f6f9d3a7c1 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-9b4a72a38a9c07c192f92d6cf883dfb65e04ec3553e7b85a0d6f356f4ef55aa7.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-0c3bf4ab99e5ef1c2100c82611aeaf4fe7ffe5734a57567dfdfea1a78cfbb3ee.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n p.\"id\" as \"item_id!\",\n p.\"createdAt\" as \"created_at!\",\n p.\"updatedAt\" as \"updated_at!\",\n p.\"deletedAt\" as \"deleted_at?\",\n p.\"parentId\" as \"parent_project_id?\",\n uh.\"updatedAt\" as \"viewed_at?\"\n FROM\n \"Project\" p\n LEFT JOIN\n \"UserHistory\" uh ON uh.\"itemId\" = p.\"id\"\n AND uh.\"userId\" = $1\n AND uh.\"itemType\" = 'project'\n WHERE\n p.\"id\" = ANY($2)\n ORDER BY\n p.\"updatedAt\" DESC\n ",+ "query": "\n SELECT\n p.\"id\" as \"item_id!\",\n p.\"createdAt\" as \"created_at!\",\n p.\"updatedAt\" as \"updated_at!\",\n p.\"deletedAt\" as \"deleted_at?\",\n p.\"parentId\" as \"parent_project_id?\",\n uh.\"updatedAt\" as \"viewed_at?\",\n p.\"userId\" as \"user_id\",\n p.\"name\"\n FROM\n \"Project\" p\n LEFT JOIN\n \"UserHistory\" uh ON uh.\"itemId\" = p.\"id\"\n AND uh.\"userId\" = $1\n AND uh.\"itemType\" = 'project'\n WHERE\n p.\"id\" = ANY($2)\n ORDER BY\n p.\"updatedAt\" DESC\n ","describe": {"columns": [{@@ -32,6 +32,16 @@"ordinal": 5,"name": "viewed_at?","type_info": "Timestamp"+ },+ {+ "ordinal": 6,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "name",+ "type_info": "Text"}],"parameters": {@@ -46,8 +56,10 @@false,true,true,+ false,+ false,false]},- "hash": "9b4a72a38a9c07c192f92d6cf883dfb65e04ec3553e7b85a0d6f356f4ef55aa7"+ "hash": "0c3bf4ab99e5ef1c2100c82611aeaf4fe7ffe5734a57567dfdfea1a78cfbb3ee"}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-7756867bf7e7a0530c155ad9f266f7416f8f40ade686ea78dabf97d4a3b77f65.json b/rust/cloud-storage/macro_db_client/.sqlx/query-7756867bf7e7a0530c155ad9f266f7416f8f40ade686ea78dabf97d4a3b77f65.jsonnew file mode 100644index 0000000000..0f653d76af--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-7756867bf7e7a0530c155ad9f266f7416f8f40ade686ea78dabf97d4a3b77f65.json@@ -0,0 +1,71 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n c.\"id\" as \"item_id!\",\n c.\"owner\" as \"owner\",\n c.\"fileType\" as \"file_type\",\n c.\"name\" as \"file_name\",\n c.\"createdAt\" as \"created_at!\",\n c.\"updatedAt\" as \"updated_at!\",\n c.\"deletedAt\" as \"deleted_at?\",\n uh.\"updatedAt\" as \"viewed_at?\",\n c.\"projectId\" as \"project_id?\"\n FROM\n \"Document\" c\n LEFT JOIN\n \"UserHistory\" uh ON uh.\"itemId\" = c.\"id\"\n AND uh.\"userId\" = $1\n AND uh.\"itemType\" = 'document'\n WHERE\n c.\"id\" = ANY($2)\n ORDER BY\n c.\"updatedAt\" DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "item_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "file_type",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "file_name",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at!",+ "type_info": "Timestamp"+ },+ {+ "ordinal": 5,+ "name": "updated_at!",+ "type_info": "Timestamp"+ },+ {+ "ordinal": 6,+ "name": "deleted_at?",+ "type_info": "Timestamp"+ },+ {+ "ordinal": 7,+ "name": "viewed_at?",+ "type_info": "Timestamp"+ },+ {+ "ordinal": 8,+ "name": "project_id?",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ false,+ false,+ false,+ true,+ false,+ true+ ]+ },+ "hash": "7756867bf7e7a0530c155ad9f266f7416f8f40ade686ea78dabf97d4a3b77f65"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-7e8af5b9c65f85d340332199ee9f3ec43f5f0132b187cbff40a8086a0c548995.json b/rust/cloud-storage/macro_db_client/.sqlx/query-7e8af5b9c65f85d340332199ee9f3ec43f5f0132b187cbff40a8086a0c548995.jsondeleted file mode 100644index 4ef502a5aa..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-7e8af5b9c65f85d340332199ee9f3ec43f5f0132b187cbff40a8086a0c548995.json+++ /dev/null@@ -1,53 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n c.\"id\" as \"item_id!\",\n c.\"createdAt\" as \"created_at!\",\n c.\"updatedAt\" as \"updated_at!\",\n c.\"deletedAt\" as \"deleted_at?\",\n uh.\"updatedAt\" as \"viewed_at?\",\n c.\"projectId\" as \"project_id?\"\n FROM\n \"Document\" c\n LEFT JOIN\n \"UserHistory\" uh ON uh.\"itemId\" = c.\"id\"\n AND uh.\"userId\" = $1\n AND uh.\"itemType\" = 'document'\n WHERE\n c.\"id\" = ANY($2)\n ORDER BY\n c.\"updatedAt\" DESC\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "item_id!",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "created_at!",- "type_info": "Timestamp"- },- {- "ordinal": 2,- "name": "updated_at!",- "type_info": "Timestamp"- },- {- "ordinal": 3,- "name": "deleted_at?",- "type_info": "Timestamp"- },- {- "ordinal": 4,- "name": "viewed_at?",- "type_info": "Timestamp"- },- {- "ordinal": 5,- "name": "project_id?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray"- ]- },- "nullable": [- false,- false,- false,- true,- false,- true- ]- },- "hash": "7e8af5b9c65f85d340332199ee9f3ec43f5f0132b187cbff40a8086a0c548995"-}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1d6e4800a6f297b505d4fa0cc84ac66002ff276389ca3ba736a417cca0b04d35.json b/rust/cloud-storage/macro_db_client/.sqlx/query-c2f19d911d10a576d01505d6da90f66fad4698c52efa69d3b4a03324c09b87a7.jsonsimilarity index 60%rename from rust/cloud-storage/macro_db_client/.sqlx/query-1d6e4800a6f297b505d4fa0cc84ac66002ff276389ca3ba736a417cca0b04d35.jsonrename to rust/cloud-storage/macro_db_client/.sqlx/query-c2f19d911d10a576d01505d6da90f66fad4698c52efa69d3b4a03324c09b87a7.jsonindex 9799f27621..0596339115 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-1d6e4800a6f297b505d4fa0cc84ac66002ff276389ca3ba736a417cca0b04d35.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-c2f19d911d10a576d01505d6da90f66fad4698c52efa69d3b4a03324c09b87a7.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n c.\"id\" as \"item_id!\",\n c.\"createdAt\" as \"created_at!\",\n c.\"updatedAt\" as \"updated_at!\",\n c.\"deletedAt\" as \"deleted_at?\",\n uh.\"updatedAt\" as \"viewed_at?\",\n c.\"projectId\" as \"project_id?\"\n FROM\n \"Chat\" c\n LEFT JOIN\n \"UserHistory\" uh ON uh.\"itemId\" = c.\"id\"\n AND uh.\"userId\" = $1\n AND uh.\"itemType\" = 'chat'\n WHERE\n c.\"id\" = ANY($2)\n ORDER BY\n c.\"updatedAt\" DESC\n ",+ "query": "\n SELECT\n c.\"id\" as \"item_id!\",\n c.\"createdAt\" as \"created_at!\",\n c.\"updatedAt\" as \"updated_at!\",\n c.\"deletedAt\" as \"deleted_at?\",\n uh.\"updatedAt\" as \"viewed_at?\",\n c.\"projectId\" as \"project_id?\",\n c.\"userId\" as \"user_id\",\n c.\"name\"\n FROM\n \"Chat\" c\n LEFT JOIN\n \"UserHistory\" uh ON uh.\"itemId\" = c.\"id\"\n AND uh.\"userId\" = $1\n AND uh.\"itemType\" = 'chat'\n WHERE\n c.\"id\" = ANY($2)\n ORDER BY\n c.\"updatedAt\" DESC\n ","describe": {"columns": [{@@ -32,6 +32,16 @@"ordinal": 5,"name": "project_id?","type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "name",+ "type_info": "Text"}],"parameters": {@@ -46,8 +56,10 @@false,true,false,- true+ true,+ false,+ false]},- "hash": "1d6e4800a6f297b505d4fa0cc84ac66002ff276389ca3ba736a417cca0b04d35"+ "hash": "c2f19d911d10a576d01505d6da90f66fad4698c52efa69d3b4a03324c09b87a7"}diff --git a/rust/cloud-storage/macro_db_client/src/chat/get.rs b/rust/cloud-storage/macro_db_client/src/chat/get.rsindex 3e116076fb..125d499fea 100644--- a/rust/cloud-storage/macro_db_client/src/chat/get.rs+++ b/rust/cloud-storage/macro_db_client/src/chat/get.rs@@ -311,6 +311,8 @@ pub struct ChatHistoryInfo {pub viewed_at: Option<DateTime<Utc>>,pub project_id: Option<String>,pub deleted_at: Option<DateTime<Utc>>,+ pub user_id: String,+ pub name: String,}/// Gets chat history information including when a user last viewed each chat@@ -333,7 +335,9 @@ pub async fn get_chat_history_info(c."updatedAt" as "updated_at!",c."deletedAt" as "deleted_at?",uh."updatedAt" as "viewed_at?",- c."projectId" as "project_id?"+ c."projectId" as "project_id?",+ c."userId" as "user_id",+ c."name"FROM"Chat" cLEFT JOIN@@ -356,6 +360,8 @@ pub async fn get_chat_history_info(.map(|row| {let info = ChatHistoryInfo {item_id: row.item_id.clone(),+ user_id: row.user_id,+ name: row.name,created_at: DateTime::<Utc>::from_naive_utc_and_offset(row.created_at, Utc),updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),viewed_at: rowdiff --git a/rust/cloud-storage/macro_db_client/src/document/get_document_history.rs b/rust/cloud-storage/macro_db_client/src/document/get_document_history.rsindex e7f19f9a1a..6d1b239ace 100644--- a/rust/cloud-storage/macro_db_client/src/document/get_document_history.rs+++ b/rust/cloud-storage/macro_db_client/src/document/get_document_history.rs@@ -1,14 +1,25 @@use chrono::{DateTime, Utc};-use serde::{Deserialize, Serialize};use std::collections::HashMap;-#[derive(Debug, Clone, Serialize, Deserialize, Default)]+#[derive(Debug, Clone, Default)]pub struct DocumentHistoryInfo {+ /// The id of the documentpub item_id: String,+ /// The owner of the document+ pub owner: String,+ /// The file type of the document+ pub file_type: Option<String>,+ /// The file name of the document+ pub file_name: String,+ /// Created atpub created_at: DateTime<Utc>,+ /// Updated atpub updated_at: DateTime<Utc>,+ /// Viewed atpub viewed_at: Option<DateTime<Utc>>,+ /// The project id of the documentpub project_id: Option<String>,+ /// Deleted atpub deleted_at: Option<DateTime<Utc>>,}@@ -28,6 +39,9 @@ pub async fn get_document_history_info(r#"SELECTc."id" as "item_id!",+ c."owner" as "owner",+ c."fileType" as "file_type",+ c."name" as "file_name",c."createdAt" as "created_at!",c."updatedAt" as "updated_at!",c."deletedAt" as "deleted_at?",@@ -55,6 +69,9 @@ pub async fn get_document_history_info(.map(|row| {let info = DocumentHistoryInfo {item_id: row.item_id.clone(),+ owner: row.owner,+ file_type: row.file_type,+ file_name: row.file_name,created_at: DateTime::<Utc>::from_naive_utc_and_offset(row.created_at, Utc),updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),viewed_at: rowdiff --git a/rust/cloud-storage/macro_db_client/src/projects/get_project_history.rs b/rust/cloud-storage/macro_db_client/src/projects/get_project_history.rsindex 6e864e51d5..33af8d8884 100644--- a/rust/cloud-storage/macro_db_client/src/projects/get_project_history.rs+++ b/rust/cloud-storage/macro_db_client/src/projects/get_project_history.rs@@ -10,6 +10,8 @@ pub struct ProjectHistoryInfo {pub viewed_at: Option<DateTime<Utc>>,pub parent_project_id: Option<String>,pub deleted_at: Option<DateTime<Utc>>,+ pub user_id: String,+ pub name: String,}/// Gets project history information including when a user last viewed each project@@ -32,7 +34,9 @@ pub async fn get_project_history_info(p."updatedAt" as "updated_at!",p."deletedAt" as "deleted_at?",p."parentId" as "parent_project_id?",- uh."updatedAt" as "viewed_at?"+ uh."updatedAt" as "viewed_at?",+ p."userId" as "user_id",+ p."name"FROM"Project" pLEFT JOIN@@ -55,6 +59,8 @@ pub async fn get_project_history_info(.map(|row| {let info = ProjectHistoryInfo {item_id: row.item_id.clone(),+ user_id: row.user_id,+ name: row.name,created_at: DateTime::<Utc>::from_naive_utc_and_offset(row.created_at, Utc),updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),viewed_at: rowdiff --git a/rust/cloud-storage/model/src/comms/mod.rs b/rust/cloud-storage/model/src/comms/mod.rsindex 8d193c7dd7..7e0d03da5e 100644--- a/rust/cloud-storage/model/src/comms/mod.rs+++ b/rust/cloud-storage/model/src/comms/mod.rs@@ -120,7 +120,9 @@ pub struct ChannelHistoryInfo {pub updated_at: DateTime<Utc>,pub viewed_at: Option<DateTime<Utc>>,pub interacted_at: Option<DateTime<Utc>>,+ /// The id of the user who created the channelpub user_id: String,+ /// The string value of the channel typepub channel_type: String,}diff --git a/rust/cloud-storage/models_search/src/channel.rs b/rust/cloud-storage/models_search/src/channel.rsindex a260bcd1f8..c5bc611d7f 100644--- a/rust/cloud-storage/models_search/src/channel.rs+++ b/rust/cloud-storage/models_search/src/channel.rs@@ -8,17 +8,21 @@ use utoipa::ToSchema;#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct ChannelSearchResult {/// The channel message id- pub message_id: String,+ /// This is only prsent if the search result is on the message content+ pub message_id: Option<String>,/// The channel message thread idpub thread_id: Option<String>,/// The sender id- pub sender_id: String,- /// The highlights for the channel message- pub highlight: SearchHighlight,+ /// This is only prsent if the search result is on the message content+ pub sender_id: Option<String>,/// When the channel message was created- pub created_at: i64,+ /// This is only prsent if the search result is on the message content+ pub created_at: Option<i64>,/// When the channel message was last updated- pub updated_at: i64,+ /// This is only prsent if the search result is on the message content+ pub updated_at: Option<i64>,+ /// The highlights for the channel message+ pub highlight: SearchHighlight,/// The score of the result#[serde(skip_serializing_if = "Option::is_none")]pub score: Option<f64>,@@ -146,25 +150,6 @@ pub struct SimpleChannelSearchReponseBaseItem<T> {pub type SimpleChannelSearchReponseItem =SimpleChannelSearchReponseBaseItem<crate::TimestampSeconds>;-impl From<opensearch_client::search::channels::ChannelMessageSearchResponse>- for SimpleChannelSearchReponseItem-{- fn from(response: opensearch_client::search::channels::ChannelMessageSearchResponse) -> Self {- Self {- channel_id: response.channel_id,- channel_type: response.channel_type,- org_id: response.org_id,- message_id: response.message_id,- thread_id: response.thread_id,- sender_id: response.sender_id,- mentions: response.mentions,- created_at: response.created_at.into(),- updated_at: response.updated_at.into(),- highlight: response.highlight.into(),- }- }-}-#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct SimpleChannelSearchResponse {/// List containing results from channels.diff --git a/rust/cloud-storage/models_search/src/chat.rs b/rust/cloud-storage/models_search/src/chat.rsindex 4ab87dbe64..3aa7026203 100644--- a/rust/cloud-storage/models_search/src/chat.rs+++ b/rust/cloud-storage/models_search/src/chat.rs@@ -9,15 +9,13 @@ use crate::{MatchType, SearchHighlight, SearchOn, SearchResponseItem};#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct ChatMessageSearchResult {/// The chat message id for the chat- pub chat_message_id: String,+ /// This is only present if the search match was on the chat message content+ pub chat_message_id: Option<String>,/// The role of the chat message- pub role: String,+ /// This is only present if the search match was on the chat message content+ pub role: Option<String>,/// The highlights for the chat messagepub highlight: SearchHighlight,- /// When the search chat was last updated- pub updated_at: i64,- /// The title of the chat- pub title: String,/// The score of the result#[serde(skip_serializing_if = "Option::is_none")]pub score: Option<f64>,@@ -140,20 +138,6 @@ pub struct SimpleChatSearchResponseBaseItem<T> {pub type SimpleChatSearchResponseItem = SimpleChatSearchResponseBaseItem<crate::TimestampSeconds>;-impl From<opensearch_client::search::chats::ChatSearchResponse> for SimpleChatSearchResponseItem {- fn from(response: opensearch_client::search::chats::ChatSearchResponse) -> Self {- Self {- chat_id: response.chat_id,- chat_message_id: response.chat_message_id,- user_id: response.user_id,- role: response.role,- updated_at: response.updated_at.into(),- title: response.title,- highlight: response.highlight.into(),- }- }-}-#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct SimpleChatSearchResponse {/// List containing results from chats.diff --git a/rust/cloud-storage/models_search/src/chat/test.rs b/rust/cloud-storage/models_search/src/chat/test.rsindex 886dd7e46d..112681d9ea 100644--- a/rust/cloud-storage/models_search/src/chat/test.rs+++ b/rust/cloud-storage/models_search/src/chat/test.rs@@ -213,19 +213,15 @@ fn test_search_response_item_to_chat_response_item_with_metadata() {let search_item = SearchResponseItem {results: vec![ChatMessageSearchResult {- chat_message_id: "msg_1".to_string(),- role: "user".to_string(),+ chat_message_id: Some("msg_1".to_string()),+ role: Some("user".to_string()),highlight: SearchHighlight::default(),- updated_at: 1234567890,- title: "Test".to_string(),score: None,},ChatMessageSearchResult {- chat_message_id: "msg_2".to_string(),- role: "assistant".to_string(),+ chat_message_id: Some("msg_2".to_string()),+ role: Some("assistant".to_string()),highlight: SearchHighlight::default(),- updated_at: 1234567891,- title: "Test".to_string(),score: None,},],@@ -245,11 +241,17 @@ fn test_search_response_item_to_chat_response_item_with_metadata() {assert_eq!(chat_response.name, "hello");assert_eq!(chat_response.chat_search_results.len(), 2);assert_eq!(- chat_response.chat_search_results[0].chat_message_id,+ chat_response.chat_search_results[0]+ .chat_message_id+ .as_ref()+ .unwrap(),"msg_1");assert_eq!(- chat_response.chat_search_results[1].chat_message_id,+ chat_response.chat_search_results[1]+ .chat_message_id+ .as_ref()+ .unwrap(),"msg_2");}@@ -264,11 +266,9 @@ fn test_serialization_equivalence() {chat_id: "chat_123".to_string(),user_id: "user_456".to_string(),chat_search_results: vec![ChatMessageSearchResult {- chat_message_id: "msg_1".to_string(),- role: "user".to_string(),+ chat_message_id: Some("msg_1".to_string()),+ role: Some("user".to_string()),highlight: SearchHighlight::default(),- updated_at: 1234567890,- title: "Test Chat".to_string(),score: None,}],};@@ -276,11 +276,9 @@ fn test_serialization_equivalence() {// Create the same thing via SearchResponseItem conversionlet search_item = SearchResponseItem {results: vec![ChatMessageSearchResult {- chat_message_id: "msg_1".to_string(),- role: "user".to_string(),+ chat_message_id: Some("msg_1".to_string()),+ role: Some("user".to_string()),highlight: SearchHighlight::default(),- updated_at: 1234567890,- title: "Test Chat".to_string(),score: None,}],metadata: ChatSearchMetadata {diff --git a/rust/cloud-storage/models_search/src/document.rs b/rust/cloud-storage/models_search/src/document.rsindex 967c2f7cbb..f65f7f734b 100644--- a/rust/cloud-storage/models_search/src/document.rs+++ b/rust/cloud-storage/models_search/src/document.rs@@ -10,14 +10,13 @@ use crate::{MatchType, SearchHighlight, SearchOn, SearchResponseItem};pub struct DocumentSearchResult {/// The node id for the document./// This is only useful for markdown at the moment- pub node_id: String,+ /// This will only be provided if the match was on content+ pub node_id: Option<String>,/// The highlights for the documentpub highlight: SearchHighlight,/// The raw content of the document./// This is only included for markdown files and will be the raw json node of the matchpub raw_content: Option<String>,- /// When the search document was last updated- pub updated_at: i64,/// The score of the result#[serde(skip_serializing_if = "Option::is_none")]pub score: Option<f64>,@@ -38,7 +37,7 @@ pub struct DocumentSearchResponseItem {/// The name of the documentpub document_name: String,/// The file type of the document- pub file_type: String,+ pub file_type: Option<String>,/// The search results for the document/// This may be empty if the search result match was on the document name onlypub document_search_results: Vec<DocumentSearchResult>,@@ -74,7 +73,7 @@ pub struct DocumentSearchMetadata {/// The id of the owner of the documentpub owner_id: String,/// The file type of the document- pub file_type: String,+ pub file_type: Option<String>,}impl From<SearchResponseItem<DocumentSearchResult, DocumentSearchMetadata>>@@ -124,23 +123,6 @@ pub struct SimpleDocumentSearchResponseBaseItem<T> {pub type SimpleDocumentSearchResponseItem =SimpleDocumentSearchResponseBaseItem<crate::TimestampSeconds>;-impl From<opensearch_client::search::documents::DocumentSearchResponse>- for SimpleDocumentSearchResponseItem-{- fn from(response: opensearch_client::search::documents::DocumentSearchResponse) -> Self {- Self {- document_id: response.document_id,- document_name: response.document_name,- node_id: response.node_id,- owner_id: response.owner_id,- file_type: response.file_type,- updated_at: response.updated_at.into(),- highlight: response.highlight.into(),- raw_content: response.raw_content,- }- }-}-#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct SimpleDocumentSearchResponse {/// List containing results from documents.diff --git a/rust/cloud-storage/models_search/src/email.rs b/rust/cloud-storage/models_search/src/email.rsindex b2ea83cc81..7b63d249e8 100644--- a/rust/cloud-storage/models_search/src/email.rs+++ b/rust/cloud-storage/models_search/src/email.rs@@ -1,4 +1,4 @@-use crate::{MatchType, SearchHighlight, SearchOn, SearchResponseItem};+use crate::{MatchType, SearchHighlight, SearchOn};use item_filters::EmailFilters;use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -8,19 +8,24 @@ use utoipa::ToSchema;#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct EmailSearchResult {/// The email message id.- pub message_id: String,- pub subject: Option<String>,- pub sender: String,+ /// This is only present if the search result is on the message content+ pub message_id: Option<String>,+ /// The sender+ /// This is only present if the search result is on the message content+ pub sender: Option<String>,+ /// This is only present if the search result is on the message contentpub recipients: Vec<String>,+ /// This is only present if the search result is on the message contentpub cc: Vec<String>,+ /// This is only present if the search result is on the message contentpub bcc: Vec<String>,+ /// This is only present if the search result is on the message contentpub labels: Vec<String>,- /// The highlights for the email message- pub highlight: SearchHighlight,- /// When the search email message was last updated- pub updated_at: i64,/// When the email message was sent+ /// This is only present if the search result is on the message contentpub sent_at: Option<i64>,+ /// The highlights for the email message+ pub highlight: SearchHighlight,/// The score of the result#[serde(skip_serializing_if = "Option::is_none")]pub score: Option<f64>,@@ -33,10 +38,14 @@ pub struct EmailSearchResponseItem {/// These field names are being aligned across all item types/// for consistency in our data model.pub id: String,- /// email threads don't have names, but keeping this here for consistency with other search items+ /// Subject of the email threadpub name: Option<String>,pub owner_id: String,+ /// The subject of the email+ /// This is only present if the search result is on the message content+ pub subject: Option<String>,+/// The id of the email threadpub thread_id: String,/// The id of the owner of the email thread@@ -68,19 +77,6 @@ pub struct EmailSearchMetadata {pub user_id: String,}-impl From<SearchResponseItem<EmailSearchResult, EmailSearchMetadata>> for EmailSearchResponseItem {- fn from(response: SearchResponseItem<EmailSearchResult, EmailSearchMetadata>) -> Self {- EmailSearchResponseItem {- id: response.metadata.thread_id.clone(),- owner_id: response.metadata.user_id.clone(),- name: None,- thread_id: response.metadata.thread_id.clone(),- user_id: response.metadata.user_id.clone(),- email_message_search_results: response.results,- }- }-}-/// The document search response object#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct EmailSearchResponse {@@ -145,28 +141,6 @@ pub struct SimpleEmailSearchResponseBaseItem<T> {pub type SimpleEmailSearchResponseItem = SimpleEmailSearchResponseBaseItem<crate::TimestampSeconds>;-impl From<opensearch_client::search::emails::EmailSearchResponse>- for SimpleEmailSearchResponseItem-{- fn from(response: opensearch_client::search::emails::EmailSearchResponse) -> Self {- Self {- thread_id: response.thread_id,- message_id: response.message_id,- sender: response.sender,- recipients: response.recipients,- cc: response.cc,- bcc: response.bcc,- labels: response.labels,- link_id: response.link_id,- user_id: response.user_id,- updated_at: response.updated_at.into(),- sent_at: response.sent_at.map(|t| t.into()),- subject: response.subject,- highlight: response.highlight.into(),- }- }-}-#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct SimpleEmailSearchResponse {/// List containing results from emails.diff --git a/rust/cloud-storage/models_search/src/lib.rs b/rust/cloud-storage/models_search/src/lib.rsindex 2210349ea1..15ee2febbf 100644--- a/rust/cloud-storage/models_search/src/lib.rs+++ b/rust/cloud-storage/models_search/src/lib.rs@@ -9,9 +9,12 @@ pub mod document;pub mod email;pub mod project;pub mod score;+mod simple;pub mod timestamp;pub mod unified;+pub use simple::*;+pub use timestamp::*;#[derive(diff --git a/rust/cloud-storage/models_search/src/project.rs b/rust/cloud-storage/models_search/src/project.rsindex 303437915c..81ae03c1fa 100644--- a/rust/cloud-storage/models_search/src/project.rs+++ b/rust/cloud-storage/models_search/src/project.rs@@ -119,21 +119,6 @@ pub struct SimpleProjectSearchResponseBaseItem<T> {pub type SimpleProjectSearchResponseItem =SimpleProjectSearchResponseBaseItem<crate::TimestampSeconds>;-impl From<opensearch_client::search::projects::ProjectSearchResponse>- for SimpleProjectSearchResponseItem-{- fn from(response: opensearch_client::search::projects::ProjectSearchResponse) -> Self {- Self {- project_id: response.project_id,- updated_at: response.updated_at.into(),- created_at: response.created_at.into(),- project_name: response.project_name,- user_id: response.user_id,- highlight: response.highlight.into(),- }- }-}-#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct SimpleProjectSearchResponse {/// List containing results from projects.diff --git a/rust/cloud-storage/models_search/src/simple.rs b/rust/cloud-storage/models_search/src/simple.rsnew file mode 100644index 0000000000..2c80b9b112--- /dev/null+++ b/rust/cloud-storage/models_search/src/simple.rs@@ -0,0 +1,126 @@+use utoipa::ToSchema;++/// The search service version of a highlight+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct Highlight {+ /// If the match was on the entity name, this will be present with that highlight+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// If the match was on the entity content, this will provide a list of highlights+ /// for each content match+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub content: Vec<String>,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+pub struct SearchGotoDocument {+ /// The node id of the document+ /// This can be a stringified page number 0-indexed for pdf/docx files,+ /// or it can be a unique id that is used in lexical for markdown files.+ pub node_id: String,+ /// The raw content of the document+ pub raw_content: Option<String>,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+pub struct SearchGotoChat {+ /// The chat message id+ pub chat_message_id: String,+ /// The role of the chat message+ pub role: String,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+pub struct SearchGotoEmail {+ /// The email message id+ pub email_message_id: String,+ pub bcc: Vec<String>,+ pub cc: Vec<String>,+ pub labels: Vec<String>,+ pub sent_at: Option<i64>,+ pub sender: String,+ pub recipients: Vec<String>,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+pub struct SearchGotoChannel {+ /// The channel message id+ pub channel_message_id: String,+}++/// The search service version of a goto+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+#[serde(untagged)]+pub enum SearchGotoContent {+ Documents(SearchGotoDocument),+ Chats(SearchGotoChat),+ Emails(SearchGotoEmail),+ Channels(SearchGotoChannel),+}++impl From<opensearch_client::search::model::SearchGotoContent> for SearchGotoContent {+ fn from(goto: opensearch_client::search::model::SearchGotoContent) -> Self {+ match goto {+ opensearch_client::search::model::SearchGotoContent::Documents(a) => {+ SearchGotoContent::Documents(SearchGotoDocument {+ node_id: a.node_id,+ raw_content: a.raw_content,+ })+ }+ opensearch_client::search::model::SearchGotoContent::Chats(a) => {+ SearchGotoContent::Chats(SearchGotoChat {+ chat_message_id: a.chat_message_id,+ role: a.role,+ })+ }+ opensearch_client::search::model::SearchGotoContent::Emails(a) => {+ SearchGotoContent::Emails(SearchGotoEmail {+ email_message_id: a.email_message_id,+ bcc: a.bcc,+ cc: a.cc,+ labels: a.labels,+ sent_at: a.sent_at,+ sender: a.sender,+ recipients: a.recipients,+ })+ }+ opensearch_client::search::model::SearchGotoContent::Channels(a) => {+ SearchGotoContent::Channels(SearchGotoChannel {+ channel_message_id: a.channel_message_id,+ })+ }+ }+ }+}++/// Simple response item to mimic what we get back from opensearch+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct SimpleSearchResponseItem {+ pub entity_id: String,+ pub entity_type: String,+ pub score: Option<f64>,+ pub highlight: Highlight,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub goto: Option<SearchGotoContent>,+}++/// The response for simple search+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct SimpleSearchResponse {+ pub results: Vec<SimpleSearchResponseItem>,+}++impl From<opensearch_client::search::model::SearchHit> for SimpleSearchResponseItem {+ fn from(hit: opensearch_client::search::model::SearchHit) -> Self {+ Self {+ entity_id: hit.entity_id,+ entity_type: hit.entity_type.to_string(),+ score: hit.score,+ highlight: Highlight {+ name: hit.highlight.name,+ content: hit.highlight.content,+ },+ goto: hit.goto.map(|a| a.into()),+ }+ }+}diff --git a/rust/cloud-storage/models_search/src/unified.rs b/rust/cloud-storage/models_search/src/unified.rsindex 2d3c900832..71a28ac961 100644--- a/rust/cloud-storage/models_search/src/unified.rs+++ b/rust/cloud-storage/models_search/src/unified.rs@@ -162,79 +162,6 @@ pub enum SimpleUnifiedSearchResponseBaseItem<T> {pub type SimpleUnifiedSearchResponseItem =SimpleUnifiedSearchResponseBaseItem<crate::TimestampSeconds>;-impl From<opensearch_client::search::unified::UnifiedSearchResponse>- for SimpleUnifiedSearchResponseItem-{- fn from(response: opensearch_client::search::unified::UnifiedSearchResponse) -> Self {- match response {- opensearch_client::search::unified::UnifiedSearchResponse::Document(a) => {- SimpleUnifiedSearchResponseItem::Document(SimpleDocumentSearchResponseBaseItem {- document_id: a.document_id,- document_name: a.document_name,- node_id: a.node_id,- owner_id: a.owner_id,- file_type: a.file_type,- updated_at: a.updated_at.into(),- highlight: a.highlight.into(),- raw_content: a.raw_content,- })- }- opensearch_client::search::unified::UnifiedSearchResponse::Chat(a) => {- SimpleUnifiedSearchResponseItem::Chat(SimpleChatSearchResponseBaseItem {- chat_id: a.chat_id,- chat_message_id: a.chat_message_id,- user_id: a.user_id,- role: a.role,- title: a.title,- highlight: a.highlight.into(),- updated_at: a.updated_at.into(),- })- }- opensearch_client::search::unified::UnifiedSearchResponse::Email(a) => {- SimpleUnifiedSearchResponseItem::Email(SimpleEmailSearchResponseBaseItem {- thread_id: a.thread_id,- message_id: a.message_id,- subject: a.subject,- sender: a.sender,- recipients: a.recipients,- cc: a.cc,- bcc: a.bcc,- labels: a.labels,- link_id: a.link_id,- user_id: a.user_id,- updated_at: a.updated_at.into(),- sent_at: a.sent_at.map(|a| a.into()),- highlight: a.highlight.into(),- })- }- opensearch_client::search::unified::UnifiedSearchResponse::ChannelMessage(a) => {- SimpleUnifiedSearchResponseItem::Channel(SimpleChannelSearchReponseBaseItem {- channel_id: a.channel_id,- channel_type: a.channel_type,- org_id: a.org_id,- message_id: a.message_id,- thread_id: a.thread_id,- sender_id: a.sender_id,- mentions: a.mentions,- created_at: a.created_at.into(),- updated_at: a.updated_at.into(),- highlight: a.highlight.into(),- })- }- opensearch_client::search::unified::UnifiedSearchResponse::Project(a) => {- SimpleUnifiedSearchResponseItem::Project(SimpleProjectSearchResponseBaseItem {- project_id: a.project_id,- project_name: a.project_name,- user_id: a.user_id,- created_at: a.created_at.into(),- updated_at: a.updated_at.into(),- highlight: a.highlight.into(),- })- }- }- }-}-#[derive(Debug, Serialize, Deserialize, ToSchema, Default)]pub struct SimpleUnifiedSearchBaseResponse<T> {pub results: Vec<SimpleUnifiedSearchResponseBaseItem<T>>,diff --git a/rust/cloud-storage/opensearch_client/Cargo.toml b/rust/cloud-storage/opensearch_client/Cargo.tomlindex a0cf0041b6..022d95a270 100644--- a/rust/cloud-storage/opensearch_client/Cargo.toml+++ b/rust/cloud-storage/opensearch_client/Cargo.toml@@ -15,7 +15,7 @@ uuid = { workspace = true }[dependencies]anyhow = { workspace = true }opensearch = { version = "2.3.0" }-opensearch_query_builder = { version = "0.2.1", default-features = false }+opensearch_query_builder = { version = "0.2.2", default-features = false }serde = { workspace = true }serde_json = { workspace = true }thiserror = { workspace = true }diff --git a/rust/cloud-storage/opensearch_client/examples/channel_message_search_args.rs b/rust/cloud-storage/opensearch_client/examples/channel_message_search_args.rsdeleted file mode 100644index ffd16c01c3..0000000000--- a/rust/cloud-storage/opensearch_client/examples/channel_message_search_args.rs+++ /dev/null@@ -1,20 +0,0 @@-use opensearch_client::search::channels::ChannelMessageSearchArgs;--fn main() {- let advanced_args = ChannelMessageSearchArgs {- terms: vec!["project".to_string(), "deadline".to_string()],- user_id: "user456".to_string(),- channel_ids: vec!["general".to_string(), "development".to_string()],- page: 1,- page_size: 20,- match_type: "exact".to_string(),- thread_ids: vec!["thread1".to_string(), "thread2".to_string()],- mentions: vec!["@alice".to_string(), "@bob".to_string()],- ..Default::default()- };-- match advanced_args.build() {- Ok(json) => println!("{}", serde_json::to_string_pretty(&json).unwrap()),- Err(e) => eprintln!("Error building advanced query: {:?}", e),- }-}diff --git a/rust/cloud-storage/opensearch_client/examples/delete_document.rs b/rust/cloud-storage/opensearch_client/examples/delete_document.rsdeleted file mode 100644index 0e1dc2a2cf..0000000000--- a/rust/cloud-storage/opensearch_client/examples/delete_document.rs+++ /dev/null@@ -1,17 +0,0 @@-use anyhow::Context;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- println!("DELETING DOCUMENT");- client- .delete_document("33591bbc-6a78-4748-93ca-8c9483201059")- .await?;-- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/delete_project.rs b/rust/cloud-storage/opensearch_client/examples/delete_project.rsdeleted file mode 100644index 347400ca2e..0000000000--- a/rust/cloud-storage/opensearch_client/examples/delete_project.rs+++ /dev/null@@ -1,36 +0,0 @@-use anyhow::Context;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- println!("Client created, checking health...");- client.health().await?;- println!("Health check passed");-- // Project IDs to delete (matching the ones from upsert_project.rs)- let project_ids = ["proj_001", "proj_002", "proj_003", "proj_004", "proj_005"];-- println!("Deleting {} projects...", project_ids.len());-- for (i, project_id) in project_ids.iter().enumerate() {- println!(- "Deleting project {}/{}: {}",- i + 1,- project_ids.len(),- project_id- );-- match client.delete_project(project_id).await {- Ok(()) => println!("✓ Successfully deleted project {}", project_id),- Err(e) => println!("✗ Failed to delete project {}: {}", project_id, e),- }- }-- println!("Finished deleting projects");- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/delete_project_bulk.rs b/rust/cloud-storage/opensearch_client/examples/delete_project_bulk.rsdeleted file mode 100644index 9fb1bf542a..0000000000--- a/rust/cloud-storage/opensearch_client/examples/delete_project_bulk.rs+++ /dev/null@@ -1,116 +0,0 @@-use anyhow::Context;-use opensearch_client::date_format::EpochSeconds;-use opensearch_client::upsert::project::UpsertProjectArgs;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- println!("Client created, checking health...");- client.health().await?;- println!("Health check passed");-- // Sample project data to create- let sample_projects = vec![- UpsertProjectArgs {- project_id: "bulk_proj_001".to_string(),- user_id: "user_bulk_test".to_string(),- project_name: "Bulk Test Project 1".to_string(),- created_at_seconds: EpochSeconds::new(1642723200)?, // 2022-01-21 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642723200)?,- },- UpsertProjectArgs {- project_id: "bulk_proj_002".to_string(),- user_id: "user_bulk_test".to_string(),- project_name: "Bulk Test Project 2".to_string(),- created_at_seconds: EpochSeconds::new(1642809600)?, // 2022-01-22 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642809600)?,- },- UpsertProjectArgs {- project_id: "bulk_proj_003".to_string(),- user_id: "user_bulk_test".to_string(),- project_name: "Bulk Test Project 3".to_string(),- created_at_seconds: EpochSeconds::new(1642896000)?, // 2022-01-23 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642896000)?,- },- UpsertProjectArgs {- project_id: "bulk_proj_004".to_string(),- user_id: "user_bulk_test".to_string(),- project_name: "Bulk Test Project 4".to_string(),- created_at_seconds: EpochSeconds::new(1642982400)?, // 2022-01-24 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642982400)?,- },- UpsertProjectArgs {- project_id: "bulk_proj_005".to_string(),- user_id: "user_bulk_test".to_string(),- project_name: "Bulk Test Project 5".to_string(),- created_at_seconds: EpochSeconds::new(1643068800)?, // 2022-01-25 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1643068800)?,- },- ];-- println!(- "Creating {} projects for bulk deletion test...",- sample_projects.len()- );-- // Create projects first- for (i, project) in sample_projects.iter().enumerate() {- println!(- "Creating project {}/{}: {}",- i + 1,- sample_projects.len(),- &project.project_name- );-- match client.upsert_project(project).await {- Ok(()) => println!("[OK] Successfully created project {}", project.project_id),- Err(e) => println!(- "[ERROR] Failed to create project {}: {}",- project.project_id, e- ),- }- }-- println!("\nProjects created successfully!");- println!("Now testing bulk deletion...");-- // Collect project IDs for bulk deletion- let project_ids: Vec<String> = sample_projects- .iter()- .map(|p| p.project_id.to_string())- .collect();-- println!("Deleting {} projects in bulk...", project_ids.len());- println!("Project IDs to delete: {:?}", project_ids);-- let project_count = project_ids.len();- match client.delete_project_bulk(&project_ids.clone()).await {- Ok(()) => {- println!(- "[OK] Successfully deleted all {} projects in bulk",- project_count- );- println!("Bulk deletion completed successfully!");- }- Err(e) => {- println!("[ERROR] Failed to delete projects in bulk: {}", e);- println!("Attempting individual cleanup...");-- // Fallback to individual deletion if bulk fails- for project_id in project_ids {- match client.delete_project(&project_id).await {- Ok(()) => println!("[OK] Cleaned up project {}", project_id),- Err(e) => println!("[ERROR] Failed to clean up project {}: {}", project_id, e),- }- }- }- }-- println!("Bulk deletion test completed!");- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/generate_all_upserts.rs b/rust/cloud-storage/opensearch_client/examples/generate_all_upserts.rsdeleted file mode 100644index d67d1a770f..0000000000--- a/rust/cloud-storage/opensearch_client/examples/generate_all_upserts.rs+++ /dev/null@@ -1,248 +0,0 @@-use anyhow::Context;-use macro_entrypoint::MacroEntrypoint;-use opensearch_client::{- OpensearchClient,- date_format::EpochSeconds,- upsert::{- channel_message::UpsertChannelMessageArgs, chat_message::UpsertChatMessageArgs,- document::UpsertDocumentArgs, email::UpsertEmailArgs, project::UpsertProjectArgs,- },-};-use uuid::Uuid;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- MacroEntrypoint::default().init();- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = OpensearchClient::new(url, username, password)?;-- // Test user IDs array- let test_users = [- "user_alice_123",- "user_bob_456",- "user_charlie_789",- "user_diana_012",- "user_eve_345",- ];-- // Varied document names for distinct search targets- let document_names = [- "Important Technical Architecture Blueprint",- "Marketing Campaign Strategy (Test keyword for matching: Pineapple)",- "Database Migration Guide",- "User Interface Wireframes",- "Security Audit Report",- ];-- // Varied project names- let project_names = [- "Phoenix Redesign Initiative (Test keyword for matching: Pineapple)",- "Apollo Data Pipeline",- "Mercury Authentication System",- "Venus Content Management",- "Jupiter Analytics Platform",- ];-- // Varied chat titles- let chat_titles = [- "Code Review Discussion",- "Feature Planning Session",- "Bug Triage Meeting (Test keyword for matching: Pineapple)",- "Architecture Brainstorm",- ];-- // Varied email subjects- let email_subjects = [- "Quarterly Performance Review",- "Infrastructure Upgrade Notice (Test keyword for matching: Pineapple)",- "Team Building Event Planning",- ];-- // Test health- println!("Testing OpenSearch health...");- client.health().await?;- println!("OpenSearch is healthy!");-- let now = chrono::Utc::now().timestamp();-- // Generate sample documents- println!("Generating sample documents...");- for i in 1..=5 {- let doc_args = UpsertDocumentArgs {- document_id: format!("doc_{}", i),- node_id: format!("node_{}", i),- document_name: document_names[(i - 1) % document_names.len()].to_string(),- file_type: match i % 3 {- 0 => "pdf".to_string(),- 1 => "md".to_string(),- _ => "docx".to_string(),- },- owner_id: test_users[(i - 1) % test_users.len()].to_string(),- raw_content: if i % 2 == 0 {- Some(format!(- r#"{{"type": "doc", "content": "Raw content for doc {}"}}"#,- i- ))- } else {- None- },- content: format!(- "This is the content of sample document {}. It contains important information about topic {} and references related concepts.",- i,- match i % 3 {- 0 => "architecture",- 1 => "implementation. test keyword: pineapple",- _ => "testing",- }- ),- updated_at_seconds: EpochSeconds::new(now + (i as i64) * 60)?,- };-- client.upsert_document(&doc_args).await?;- println!("Upserted document {}", i);- }-- // Generate sample projects- println!("Generating sample projects...");- for i in 1..=3 {- let project_args = UpsertProjectArgs {- project_id: format!("proj_{}", i),- user_id: test_users[(i - 1) % test_users.len()].to_string(),- project_name: project_names[(i - 1) % project_names.len()].to_string(),- created_at_seconds: EpochSeconds::new(now - (i as i64) * 86400)?,- updated_at_seconds: EpochSeconds::new(now - (i as i64) * 3600)?,- };-- client.upsert_project(&project_args).await?;- println!("Upserted project {}", i);- }-- // Generate sample channel messages- println!("Generating sample channel messages...");- for i in 1..=4 {- let channel_args = UpsertChannelMessageArgs {- channel_id: format!("channel_{}", (i % 2) + 1),- channel_type: "public".to_string(),- org_id: Some(1),- message_id: format!("msg_{}", i),- thread_id: if i > 2 {- Some("thread_1".to_string())- } else {- None- },- sender_id: test_users[(i - 1) % test_users.len()].to_string(),- mentions: if i == 2 {- vec![test_users[0].to_string(), test_users[2].to_string()]- } else {- vec![]- },- content: format!(- "This is channel message {}. Hey everyone, let's discuss the {} topic! (Distinct keyword for matching tests: Pineapple)",- i,- match i % 3 {- 0 => "project updates",- 1 => "team meeting",- _ => "technical review",- }- ),- created_at_seconds: EpochSeconds::new(now - (i as i64) * 1800)?,- updated_at_seconds: EpochSeconds::new(now - (i as i64) * 1800)?,- };-- client.upsert_channel_message(&channel_args).await?;- println!("Upserted channel message {}", i);- }-- // Generate sample chat messages- println!("Generating sample chat messages...");- for i in 1..=4 {- let chat_args = UpsertChatMessageArgs {- chat_id: format!("chat_{}", (i % 2) + 1),- chat_message_id: format!("chat_msg_{}", i),- user_id: test_users[(i - 1) % test_users.len()].to_string(),- role: if i % 2 == 0 {- "user".to_string()- } else {- "assistant".to_string()- },- created_at_seconds: EpochSeconds::new(now - (i as i64) * 900)?,- updated_at_seconds: EpochSeconds::new(now - (i as i64) * 900)?,- title: chat_titles[(i - 1) % chat_titles.len()].to_string(),- content: format!(- "This is chat message {}. {}",- i,- match i % 3 {- 0 =>- "Can you help me understand how the authentication system works? (Distinct keyword for matching tests: Pineapple)",- 1 =>- "Sure! The authentication system uses JWT tokens for session management. (Distinct test keyword: Pineapple)",- _ =>- "That makes sense. What about the database schema? (Distinct test keyword: Pineapple)",- }- ),- };-- client.upsert_chat_message(&chat_args).await?;- println!("Upserted chat message {}", i);- }-- // Generate sample email messages- println!("Generating sample email messages...");- for i in 1..=3 {- let email_args = UpsertEmailArgs {- thread_id: format!("thread_{}", (i % 2) + 1),- message_id: format!("email_{}", i),- sender: format!(- "{}@example.com",- test_users[(i - 1) % test_users.len()].replace("user_", "")- ),- recipients: vec![- format!("recipient{}@example.com", i),- "[email protected]".to_string(),- ],- cc: if i == 2 {- vec!["[email protected]".to_string()]- } else {- vec![]- },- bcc: vec![],- labels: vec![- "work".to_string(),- match i % 2 {- 0 => "urgent".to_string(),- _ => "info".to_string(),- },- ],- link_id: Uuid::new_v4().to_string(),- user_id: test_users[(i - 1) % test_users.len()].to_string(),- updated_at_seconds: EpochSeconds::new(now - (i as i64) * 7200)?,- subject: Some(email_subjects[(i - 1) % email_subjects.len()].to_string()),- sent_at_seconds: Some(EpochSeconds::new(now - (i as i64) * 7200)?),- content: format!(- "This is email message {}. Dear team, I wanted to update you on the {} status. Please review the attached details.",- i,- match i % 3 {- 0 => "project milestone",- 1 => "system deployment (test keyword: pineapple)",- _ => "quarterly review",- }- ),- };-- client.upsert_email_message(&email_args).await?;- println!("Upserted email message {}", i);- }-- println!("\nSuccessfully generated and upserted sample data for all indices!");- println!("Generated:");- println!("- 5 documents");- println!("- 3 projects");- println!("- 4 channel messages");- println!("- 4 chat messages");- println!("- 3 email messages");-- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/health_check.rs b/rust/cloud-storage/opensearch_client/examples/health_check.rsdeleted file mode 100644index 1ee7f3a379..0000000000--- a/rust/cloud-storage/opensearch_client/examples/health_check.rs+++ /dev/null@@ -1,20 +0,0 @@-use anyhow::Context;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- println!("Client created");-- if let Err(e) = client.health().await {- println!("Unable to connect to OpenSearch: {e}");- }-- println!("OpenSearch health check passed");-- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/query_document.rs b/rust/cloud-storage/opensearch_client/examples/query_document.rsdeleted file mode 100644index 23ba07d9a0..0000000000--- a/rust/cloud-storage/opensearch_client/examples/query_document.rs+++ /dev/null@@ -1,34 +0,0 @@-use anyhow::Context;-use opensearch_client::SearchOn;-use opensearch_client::search::documents::DocumentSearchArgs;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- let result = client- .search_documents(DocumentSearchArgs {- terms: vec!["equation".to_string()],- user_id: "user".to_string(),- document_ids: Vec::new(),- page: 0,- page_size: 10,- match_type: "partial".to_string(),- search_on: SearchOn::Content,- ids_only: false,- collapse: false,- disable_recency: false,- })- .await?;-- for document in result {- println!("{:?}", document.document_id);- println!("{:?}", document.highlight);- }-- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/search_project.rs b/rust/cloud-storage/opensearch_client/examples/search_project.rsdeleted file mode 100644index bb1951afa6..0000000000--- a/rust/cloud-storage/opensearch_client/examples/search_project.rs+++ /dev/null@@ -1,80 +0,0 @@-use anyhow::Context;-use opensearch_client::search::projects::ProjectSearchArgs;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- println!("Client created, checking health...");- client.health().await?;- println!("Health check passed");-- // Search examples based on the sample data from upsert_project.rs- let search_scenarios = vec![- ("AI", "user_123", "Search for AI projects"),- ("Research", "user_123", "Search for Research projects"),- ("Web", "user_456", "Search for Web projects"),- ("React", "user_456", "Search for React projects"),- ("Data", "user_789", "Search for Data projects"),- ("", "user_123", "Get all projects for user_123"),- ];-- for (term, user_id, description) in search_scenarios {- println!("\n--- {} ---", description);-- let search_args = ProjectSearchArgs {- terms: if term.is_empty() {- vec![]- } else {- vec![term.to_string()]- },- user_id: user_id.to_string(),- page: 0,- page_size: 10,- match_type: "exact".to_string(),- ..Default::default()- };-- match client.search_project(search_args).await {- Ok(results) => {- println!("Found {} results:", results.len());- for result in results {- println!(- " - {} ({}): {}",- result.project_id, result.user_id, result.project_name- );- }- }- Err(e) => println!("Search failed: {}", e),- }- }-- println!("\n--- Partial match search ---");- let partial_search = ProjectSearchArgs {- terms: vec!["Dev".to_string()],- user_id: "user_456".to_string(),- page: 0,- page_size: 10,- match_type: "partial".to_string(),- ..Default::default()- };-- match client.search_project(partial_search).await {- Ok(results) => {- println!("Found {} results with partial match:", results.len());- for result in results {- println!(- " - {} ({}): {}",- result.project_id, result.user_id, result.project_name- );- }- }- Err(e) => println!("Partial search failed: {}", e),- }-- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/upsert_document.rs b/rust/cloud-storage/opensearch_client/examples/upsert_document.rsdeleted file mode 100644index ecee7f6a99..0000000000--- a/rust/cloud-storage/opensearch_client/examples/upsert_document.rs+++ /dev/null@@ -1,28 +0,0 @@-use anyhow::Context;-use opensearch_client::date_format::EpochSeconds;-use opensearch_client::upsert::document::UpsertDocumentArgs;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let content = std::fs::read_to_string("fixtures/sample_file.md")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;- client- .upsert_document(&UpsertDocumentArgs {- node_id: "node-id".to_string(),- raw_content: None,- document_id: "testing-id".to_string(),- document_name: "sample_file".to_string(),- file_type: "md".to_string(),- owner_id: "macro|[email protected]".to_string(),- content,- updated_at_seconds: EpochSeconds::new(1704067200)?,- })- .await?;-- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/examples/upsert_project.rs b/rust/cloud-storage/opensearch_client/examples/upsert_project.rsdeleted file mode 100644index 895f304ccb..0000000000--- a/rust/cloud-storage/opensearch_client/examples/upsert_project.rs+++ /dev/null@@ -1,74 +0,0 @@-use anyhow::Context;-use opensearch_client::date_format::EpochSeconds;-use opensearch_client::upsert::project::UpsertProjectArgs;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- println!("Client created, checking health...");- client.health().await?;- println!("Health check passed");-- // Sample project data- let sample_projects = vec![- UpsertProjectArgs {- project_id: "proj_001".to_string(),- user_id: "user_123".to_string(),- project_name: "AI Research Project".to_string(),- created_at_seconds: EpochSeconds::new(1642723200)?, // 2022-01-21 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642723200)?,- },- UpsertProjectArgs {- project_id: "proj_002".to_string(),- user_id: "user_123".to_string(),- project_name: "Machine Learning Models".to_string(),- created_at_seconds: EpochSeconds::new(1642809600)?, // 2022-01-22 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642809600)?,- },- UpsertProjectArgs {- project_id: "proj_003".to_string(),- user_id: "user_456".to_string(),- project_name: "Web Development".to_string(),- created_at_seconds: EpochSeconds::new(1642896000)?, // 2022-01-23 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642896000)?,- },- UpsertProjectArgs {- project_id: "proj_004".to_string(),- user_id: "user_456".to_string(),- project_name: "React Frontend".to_string(),- created_at_seconds: EpochSeconds::new(1642982400)?, // 2022-01-24 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1642982400)?,- },- UpsertProjectArgs {- project_id: "proj_005".to_string(),- user_id: "user_789".to_string(),- project_name: "Data Analysis Pipeline".to_string(),- created_at_seconds: EpochSeconds::new(1643068800)?, // 2022-01-25 00:00:00 UTC- updated_at_seconds: EpochSeconds::new(1643068800)?,- },- ];-- println!("Upserting {} projects...", sample_projects.len());-- for (i, project) in sample_projects.iter().enumerate() {- println!(- "Upserting project {}/{}: {}",- i + 1,- sample_projects.len(),- project.project_name- );-- match client.upsert_project(project).await {- Ok(()) => println!("✓ Successfully upserted project {}", project.project_id),- Err(e) => println!("✗ Failed to upsert project {}: {}", project.project_id, e),- }- }-- println!("Finished upserting projects");- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/src/channel_message.rs b/rust/cloud-storage/opensearch_client/src/channel_message.rsindex dcdcb52213..01049dc8d3 100644--- a/rust/cloud-storage/opensearch_client/src/channel_message.rs+++ b/rust/cloud-storage/opensearch_client/src/channel_message.rs@@ -1,9 +1,6 @@use crate::{OpensearchClient, Result, delete,- search::{- self,- channels::{ChannelMessageSearchResponse, search_channel_messages},- },+ search::{self, channels::search_channel_messages, model::SearchHit},upsert::{self, channel_message::UpsertChannelMessageArgs},};@@ -42,7 +39,7 @@ impl OpensearchClient {pub async fn search_channel_messages(&self,args: search::channels::ChannelMessageSearchArgs,- ) -> Result<Vec<ChannelMessageSearchResponse>> {+ ) -> Result<Vec<SearchHit>> {search_channel_messages(&self.inner, args).await}}diff --git a/rust/cloud-storage/opensearch_client/src/chat.rs b/rust/cloud-storage/opensearch_client/src/chat.rsindex 0c9657481b..0d83c80cb2 100644--- a/rust/cloud-storage/opensearch_client/src/chat.rs+++ b/rust/cloud-storage/opensearch_client/src/chat.rs@@ -1,6 +1,6 @@use crate::{OpensearchClient, Result, delete,- search::chats::{ChatSearchResponse, search_chats},+ search::{chats::search_chats, model::SearchHit},upsert::{self, chat_message::UpsertChatMessageArgs},};@@ -32,7 +32,7 @@ impl OpensearchClient {pub async fn search_chats(&self,args: crate::search::chats::ChatSearchArgs,- ) -> Result<Vec<ChatSearchResponse>> {+ ) -> Result<Vec<SearchHit>> {search_chats(&self.inner, args).await}diff --git a/rust/cloud-storage/opensearch_client/src/document.rs b/rust/cloud-storage/opensearch_client/src/document.rsindex eab391c7bc..88c15381c1 100644--- a/rust/cloud-storage/opensearch_client/src/document.rs+++ b/rust/cloud-storage/opensearch_client/src/document.rs@@ -1,9 +1,6 @@use crate::{OpensearchClient, Result, delete,- search::{- self,- documents::{DocumentSearchResponse, search_documents},- },+ search::{self, documents::search_documents, model::SearchHit},upsert::{self, document::UpsertDocumentArgs},};@@ -28,7 +25,7 @@ impl OpensearchClient {pub async fn search_documents(&self,args: search::documents::DocumentSearchArgs,- ) -> Result<Vec<DocumentSearchResponse>> {+ ) -> Result<Vec<SearchHit>> {search_documents(&self.inner, args).await}diff --git a/rust/cloud-storage/opensearch_client/src/email.rs b/rust/cloud-storage/opensearch_client/src/email.rsindex a6a9857987..53a3142207 100644--- a/rust/cloud-storage/opensearch_client/src/email.rs+++ b/rust/cloud-storage/opensearch_client/src/email.rs@@ -1,6 +1,9 @@use crate::{OpensearchClient, Result, delete,- search::emails::{EmailSearchArgs, EmailSearchResponse, search_emails},+ search::{+ emails::{EmailSearchArgs, search_emails},+ model::SearchHit,+ },upsert::{self, email::UpsertEmailArgs},};@@ -11,7 +14,7 @@ impl OpensearchClient {upsert::email::upsert_email_message(&self.inner, upsert_email_args).await}- pub async fn search_emails(&self, args: EmailSearchArgs) -> Result<Vec<EmailSearchResponse>> {+ pub async fn search_emails(&self, args: EmailSearchArgs) -> Result<Vec<SearchHit>> {search_emails(&self.inner, args).await}diff --git a/rust/cloud-storage/opensearch_client/src/error.rs b/rust/cloud-storage/opensearch_client/src/error.rsindex 544b594cd5..c04de995df 100644--- a/rust/cloud-storage/opensearch_client/src/error.rs+++ b/rust/cloud-storage/opensearch_client/src/error.rs@@ -44,6 +44,9 @@ pub enum OpensearchClientError {#[error("no title key is available for name search")]NoTitleKeyForNameSearch,++ #[error("bool query not built")]+ BoolQueryNotBuilt,}impl From<anyhow::Error> for OpensearchClientError {diff --git a/rust/cloud-storage/opensearch_client/src/project.rs b/rust/cloud-storage/opensearch_client/src/project.rsindex 54b642824a..bca7be1a85 100644--- a/rust/cloud-storage/opensearch_client/src/project.rs+++ b/rust/cloud-storage/opensearch_client/src/project.rs@@ -1,7 +1,10 @@use crate::{OpensearchClient, Result,delete::project::{delete_project_bulk_ids, delete_project_by_id, delete_projects_by_user_id},- search::projects::{ProjectSearchArgs, ProjectSearchResponse, search_projects},+ search::{+ model::SearchHit,+ projects::{ProjectSearchArgs, search_projects},+ },upsert::project::{UpsertProjectArgs, upsert_project},};@@ -26,10 +29,7 @@ impl OpensearchClient {/// Searches for projects in the opensearch index#[tracing::instrument(skip(self))]- pub async fn search_project(- &self,- args: ProjectSearchArgs,- ) -> Result<Vec<ProjectSearchResponse>> {+ pub async fn search_project(&self, args: ProjectSearchArgs) -> Result<Vec<SearchHit>> {search_projects(&self.inner, args).await}diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rsindex 79786c51cb..6fdcf220ce 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs@@ -1,11 +1,14 @@+use std::borrow::Cow;+use crate::Result;use crate::SearchOn;use crate::error::OpensearchClientError;use crate::search::model::MacroEm;use crate::search::query::Keys;use crate::search::query::QueryKey;-use crate::search::query::generate_name_content_query;use crate::search::query::generate_terms_must_query;+use models_opensearch::SearchEntityType;+use models_opensearch::SearchIndex;use opensearch_query_builder::*;/// A macro for generating delegation methods that forward calls to an inner field@@ -48,14 +51,16 @@ pub trait SearchQueryConfig {const ID_KEY: &'static str = "entity_id";/// Key for user idconst USER_ID_KEY: &'static str;- /// Key for title (there may not be a title key for things like channels index)- const TITLE_KEY: Option<&'static str>;+ /// Key for title+ const TITLE_KEY: &'static str;/// Content fieldconst CONTENT_KEY: &'static str = "content";+ /// The entity index for the search query+ const ENTITY_INDEX: SearchEntityType;/// Returns the default sort types that are used on the search query./// Override this method if you need custom sort logic- fn default_sort_types() -> Vec<SortType<'static>> {+ fn default_sort_types<'a>() -> Vec<SortType<'a>> {vec![SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),@@ -63,7 +68,7 @@ pub trait SearchQueryConfig {}/// Override this method if you need custom highlight logic- fn default_highlight() -> Highlight<'static> {+ fn default_highlight<'a>() -> Highlight<'a> {Highlight::new().require_field_match(true).field("content",HighlightField::new()@@ -107,6 +112,11 @@ pub struct SearchQueryBuilder<T: SearchQueryConfig> {_phantom: std::marker::PhantomData<T>,}+pub struct ContentAndNameBoolQueries<'a> {+ pub content_bool_query: Option<BoolQueryBuilder<'a>>,+ pub name_bool_query: Option<BoolQueryBuilder<'a>>,+}+impl<T: SearchQueryConfig> SearchQueryBuilder<T> {pub fn new(terms: Vec<String>) -> Self {Self {@@ -169,47 +179,145 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {self}- /// Builds the core bool query which contains all core "should" and "must" clauses- pub fn build_bool_query(&self) -> Result<BoolQueryBuilder<'static>> {- let mut bool_query = BoolQueryBuilder::new();+ /// Builds a content and name bool query+ pub fn build_content_and_name_bool_query<'a>(+ &'a self,+ ) -> Result<ContentAndNameBoolQueries<'a>> {+ let content_bool_query = match self.search_on {+ SearchOn::Name => None,+ SearchOn::NameContent | SearchOn::Content => {+ let mut bool_query = BoolQueryBuilder::new();++ // Currently, the minimum should match is always one.+ // This should of the bool query contains the ids and potentially the user_id+ bool_query.minimum_should_match(1);++ // For name OR content queries, we can build a much more simple bool query+ let term_must_array: Vec<QueryType<'a>> =+ self.build_must_term_query(SearchOn::Content)?;++ // For each item in term must array, add to bool must query+ for must in term_must_array {+ bool_query.must(must);+ }- // Currently, the minimum should match is always one.- // This should of the bool query contains the ids and potentially the user_id- bool_query.minimum_should_match(1);+ // Add any ids to the should array if provided+ if !self.ids.is_empty() {+ bool_query.should(QueryType::terms(T::ID_KEY.to_string(), self.ids.to_vec()));+ }- let term_must_array: Vec<QueryType<'static>> = self.build_must_term_query()?;+ // If we are not searching over the ids, we need to add the user_id to the should array+ if !self.ids_only {+ bool_query.should(QueryType::term(+ T::USER_ID_KEY.to_string(),+ self.user_id.clone(),+ ));+ }- tracing::trace!("term_must_array: {:?}", term_must_array);+ bool_query.must(QueryType::term("_index", T::ENTITY_INDEX.as_ref()));- // For each item in term must array, add to bool must query- for must in term_must_array {- bool_query.must(must);- }+ Some(bool_query)+ }+ };- // Add any ids to the should array if provided- if !self.ids.is_empty() {- bool_query.should(QueryType::terms(T::ID_KEY.to_string(), self.ids.to_vec()));- }+ let name_bool_query = match self.search_on {+ SearchOn::Content => None,+ SearchOn::Name | SearchOn::NameContent => {+ let mut bool_query = BoolQueryBuilder::new();- // If we are not searching over the ids, we need to add the user_id to the should array- if !self.ids_only {- bool_query.should(QueryType::term(- T::USER_ID_KEY.to_string(),- self.user_id.clone(),- ));- }+ // Currently, the minimum should match is always one.+ // This should of the bool query contains the ids and potentially the user_id+ bool_query.minimum_should_match(1);- Ok(bool_query)+ // For name OR content queries, we can build a much more simple bool query+ let term_must_array: Vec<QueryType<'a>> =+ self.build_must_term_query(SearchOn::Name)?;++ // For each item in term must array, add to bool must query+ for must in term_must_array {+ bool_query.must(must);+ }++ // Add any ids to the should array if provided+ if !self.ids.is_empty() {+ bool_query.should(QueryType::terms(T::ID_KEY.to_string(), self.ids.to_vec()));+ }++ // If we are not searching over the ids, we need to add the user_id to the should array+ if !self.ids_only {+ bool_query.should(QueryType::term(+ "user_id", // the names index only has user_id+ self.user_id.clone(),+ ));+ }++ match T::ENTITY_INDEX {+ SearchEntityType::Projects => {+ bool_query.must(QueryType::term("_index", SearchIndex::Projects.as_ref()));+ }+ _ => {+ bool_query.must(QueryType::term("_index", SearchIndex::Names.as_ref()));+ bool_query.must(QueryType::term("entity_type", T::ENTITY_INDEX.as_ref()));+ }+ }++ Some(bool_query)+ }+ };++ Ok(ContentAndNameBoolQueries {+ content_bool_query,+ name_bool_query,+ })+ }++ /// Builds the core bool query using the content_and_name_bool_queries+ /// generated from self.build_content_and_name_bool_query().+ /// They must be geneated separately as they could be modified after initially+ /// being built.+ pub fn build_bool_query<'a>(+ &self,+ content_and_name_bool_queries: ContentAndNameBoolQueries<'a>,+ ) -> Result<BoolQueryBuilder<'a>> {+ // If we have name content search, we need to combine the content and name bool queries+ // under a single root bool query+ match self.search_on {+ SearchOn::Name => Ok(content_and_name_bool_queries+ .name_bool_query+ .ok_or(OpensearchClientError::BoolQueryNotBuilt)?),+ SearchOn::Content => Ok(content_and_name_bool_queries+ .content_bool_query+ .ok_or(OpensearchClientError::BoolQueryNotBuilt)?),+ SearchOn::NameContent => {+ let mut bool_query = BoolQueryBuilder::new();++ // Currently, the minimum should match is always one.+ // This should of the bool query contains the ids and potentially the user_id+ bool_query.minimum_should_match(1);++ let content_bool_query = content_and_name_bool_queries+ .content_bool_query+ .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;+ let name_bool_query = content_and_name_bool_queries+ .name_bool_query+ .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;++ bool_query.should(content_bool_query.build().into());+ bool_query.should(name_bool_query.build().into());++ Ok(bool_query)+ }+ }}/// Builds the search request with the provided main bool query/// This will automatically wrap the bool query in a function score if/// SearchOn::NameContent is used- pub fn build_search_request(- &self,- query_object: BoolQuery<'static>,- ) -> Result<SearchRequest<'static>> {- let mut search_request = SearchRequestBuilder::new();+ pub fn build_search_request<'a>(+ &'a self,+ query_object: BoolQuery<'a>,+ ) -> Result<SearchRequest<'a>> {+ let mut search_request: SearchRequestBuilder<'a> = SearchRequestBuilder::new();// Collapse on the ID_KEY if collapse is true// or if we are searchign on Name or NameContent@@ -222,45 +330,32 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {let highlight = match self.search_on {SearchOn::Content => T::default_highlight(),- SearchOn::Name => {- if let Some(title_key) = T::TITLE_KEY {- Highlight::new().require_field_match(true).field(- title_key,- HighlightField::new()- .highlight_type("plain")- .pre_tags(vec![MacroEm::Open.to_string()])- .post_tags(vec![MacroEm::Close.to_string()])- .number_of_fragments(1),- )- } else {- return Err(OpensearchClientError::NoTitleKeyForNameSearch);- }- }- SearchOn::NameContent => {- let mut highlight = Highlight::new();- highlight = highlight.require_field_match(false);- if let Some(title_key) = T::TITLE_KEY {- highlight = highlight.field(- title_key,- HighlightField::new()- .highlight_type("plain")- .pre_tags(vec![MacroEm::Open.to_string()])- .post_tags(vec![MacroEm::Close.to_string()])- .number_of_fragments(1),- );- }-- highlight = highlight.field(- "content",+ SearchOn::Name => Highlight::new().require_field_match(true).field(+ T::TITLE_KEY,+ HighlightField::new()+ .highlight_type("plain")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(1),+ ),+ SearchOn::NameContent => Highlight::new()+ .require_field_match(false)+ .field(+ T::TITLE_KEY,HighlightField::new().highlight_type("plain").pre_tags(vec![MacroEm::Open.to_string()]).post_tags(vec![MacroEm::Close.to_string()]).number_of_fragments(1),- );-- highlight- }+ )+ .field(+ T::CONTENT_KEY,+ HighlightField::new()+ .highlight_type("plain")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(1),+ ),};search_request.highlight(highlight);@@ -314,7 +409,7 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {}/// Generates a vec of term queries to be put inside of the bool must query- pub fn build_must_term_query(&self) -> Result<Vec<QueryType<'static>>> {+ pub fn build_must_term_query<'a>(&'a self, search_on: SearchOn) -> Result<Vec<QueryType<'a>>> {let keys = Keys {title_key: T::TITLE_KEY,content_key: T::CONTENT_KEY,@@ -328,30 +423,31 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {let mut must_array = Vec::new();- match self.search_on {+ let terms: Cow<'_, [&str]> =+ Cow::Owned(self.terms.iter().map(|t| t.as_str()).collect::<Vec<&str>>());++ match search_on {SearchOn::Name => {- if let Some(title_key) = keys.title_key {- // map all terms over title key- must_array.push(generate_terms_must_query(- query_key,- &[title_key],- &self.terms,- ));- } else {- return Err(OpensearchClientError::NoTitleKeyForNameSearch);- }+ must_array.push(generate_terms_must_query(+ query_key,+ keys.title_key,+ terms,+ None,+ ));}SearchOn::Content => {// map all terms over content keymust_array.push(generate_terms_must_query(query_key,- &[keys.content_key],- &self.terms,+ keys.content_key,+ terms,+ None,));}- SearchOn::NameContent => {- must_array.push(generate_name_content_query(&keys, &self.terms));- }+ SearchOn::NameContent => unreachable!(),+ // SearchOn::NameContent => {+ // must_array.push(generate_name_content_query(&keys, &self.terms));+ // }};Ok(must_array)diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rsindex bdcac992fa..eb5d332f93 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs@@ -6,7 +6,8 @@ struct TestSearchConfig;impl SearchQueryConfig for TestSearchConfig {const USER_ID_KEY: &'static str = "test_user_id";- const TITLE_KEY: Option<&'static str> = Some("test_title");+ const TITLE_KEY: &'static str = "test_title";+ const ENTITY_INDEX: SearchEntityType = SearchEntityType::Documents;}#[test]@@ -184,7 +185,8 @@ fn test_build_bool_query() -> anyhow::Result<()> {.user_id(user_id).search_on(SearchOn::Content).ids(ids.clone());- let query = builder.build_bool_query()?;++ let query = builder.build_bool_query(builder.build_content_and_name_bool_query()?)?;let expected = serde_json::json!({"bool": {@@ -193,7 +195,8 @@ fn test_build_bool_query() -> anyhow::Result<()> {"match_phrase": {"content": "test"}- }+ },+ {"term": {"_index": "documents"}},],"should": [{@@ -222,7 +225,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {.search_on(SearchOn::Content).ids(ids.clone());- let query = builder.build_bool_query()?;+ let query = builder.build_bool_query(builder.build_content_and_name_bool_query()?)?;let expected = serde_json::json!({"bool": {@@ -232,77 +235,9 @@ fn test_build_bool_query() -> anyhow::Result<()> {"content": {"query": "test",}- }- }- ],- "should": [- {- "terms": {- "entity_id": ["id1", "id2"]- }+ },},- ],- "minimum_should_match": 1,- }- });-- assert_eq!(query.build().to_json(), expected);-- let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms)- .match_type("partial")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids_only(true)- .search_on(SearchOn::NameContent)- .ids(ids.clone());-- let query = builder.build_bool_query()?;-- let expected = serde_json::json!({- "bool": {- "must": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "test_title": {- "boost": 1000.0,- "query": "test"- }- }- },- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test"- }- }- },- {- "match": {- "test_title": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]- }- }+ {"term": {"_index": "documents"}},],"should": [{@@ -317,6 +252,75 @@ fn test_build_bool_query() -> anyhow::Result<()> {assert_eq!(query.build().to_json(), expected);+ // let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms)+ // .match_type("partial")+ // .page_size(page_size)+ // .page(page)+ // .user_id(user_id)+ // .ids_only(true)+ // .search_on(SearchOn::NameContent)+ // .ids(ids.clone());+ //+ // let query = builder.build_bool_query(builder.build_content_and_name_bool_query()?)?;+ //+ // let expected = serde_json::json!({+ // "bool": {+ // "must": [+ // {+ // "bool": {+ // "minimum_should_match": 1,+ // "should": [+ // {+ // "match_phrase_prefix": {+ // "test_title": {+ // "boost": 1000.0,+ // "query": "test"+ // }+ // }+ // },+ // {+ // "match_phrase_prefix": {+ // "content": {+ // "boost": 900.0,+ // "query": "test"+ // }+ // }+ // },+ // {+ // "match": {+ // "test_title": {+ // "boost": 0.1,+ // "minimum_should_match": "80%",+ // "query": "test"+ // }+ // }+ // },+ // {+ // "match": {+ // "content": {+ // "boost": 0.09,+ // "minimum_should_match": "1",+ // "query": "test"+ // }+ // }+ // }+ // ]+ // }+ // }+ // ],+ // "should": [+ // {+ // "terms": {+ // "entity_id": ["id1", "id2"]+ // }+ // },+ // ],+ // "minimum_should_match": 1,+ // }+ // });+ //+ // assert_eq!(query.build().to_json(), expected);+Ok(())}@@ -328,7 +332,7 @@ fn test_build_must_term_query() -> anyhow::Result<()> {.match_type("exact").search_on(SearchOn::Content);- let terms_must_vec = builder.build_must_term_query()?;+ let terms_must_vec = builder.build_must_term_query(SearchOn::Content)?;let expected = serde_json::json!({"match_phrase": {@@ -343,7 +347,7 @@ fn test_build_must_term_query() -> anyhow::Result<()> {.match_type("exact").search_on(SearchOn::Name);- let terms_must_vec = builder.build_must_term_query()?;+ let terms_must_vec = builder.build_must_term_query(SearchOn::Name)?;let expected = serde_json::json!({"match_phrase": {@@ -358,7 +362,7 @@ fn test_build_must_term_query() -> anyhow::Result<()> {.match_type("partial").search_on(SearchOn::Content);- let terms_must_vec = builder.build_must_term_query()?;+ let terms_must_vec = builder.build_must_term_query(SearchOn::Content)?;let expected = serde_json::json!({"match_phrase_prefix": {@@ -371,57 +375,6 @@ fn test_build_must_term_query() -> anyhow::Result<()> {assert_eq!(terms_must_vec.len(), 1);assert_eq!(terms_must_vec[0].to_json(), expected);- let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms)- .match_type("partial")- .search_on(SearchOn::NameContent);-- let terms_must_vec = builder.build_must_term_query()?;-- let expected = serde_json::json!({- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "test_title": {- "query": "test",- "boost": 1000.0- }- }- },- {- "match_phrase_prefix": {- "content": {- "query": "test",- "boost": 900.0- }- }- },- {- "match": {- "test_title": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]- }- });-- assert_eq!(terms_must_vec.len(), 1);- assert_eq!(terms_must_vec[0].to_json(), expected);-Ok(())}@@ -433,7 +386,7 @@ fn test_build_must_term_query_multiple_terms() -> anyhow::Result<()> {.match_type("exact").search_on(SearchOn::Content);- let terms_must_vec = builder.build_must_term_query()?;+ let terms_must_vec = builder.build_must_term_query(SearchOn::Content)?;let expected = serde_json::json!({"bool": {@@ -456,105 +409,6 @@ fn test_build_must_term_query_multiple_terms() -> anyhow::Result<()> {assert_eq!(terms_must_vec.len(), 1);assert_eq!(terms_must_vec[0].to_json(), expected);- let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms)- .match_type("partial")- .search_on(SearchOn::NameContent);-- let terms_must_vec = builder.build_must_term_query()?;-- let expected = serde_json::json!({- "bool": {- "minimum_should_match": 1,- "should": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "test_title": {- "boost": 1000.0,- "query": "test1"- }- }- },- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test1"- }- }- },- {- "match": {- "test_title": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test1"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test1"- }- }- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "test_title": {- "boost": 1000.0,- "query": "test2"- }- }- },- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test2"- }- }- },- {- "match": {- "test_title": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test2"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test2"- }- }- }- ]- }- }- ]- }- });-- assert_eq!(terms_must_vec.len(), 1);- assert_eq!(terms_must_vec[0].to_json(), expected);-Ok(())}@@ -565,7 +419,7 @@ fn test_build_must_term_query_term_with_short_last_word() -> anyhow::Result<()>.match_type("partial").search_on(SearchOn::Content);- let terms_must_vec = builder.build_must_term_query()?;+ let terms_must_vec = builder.build_must_term_query(SearchOn::Content)?;let expected = serde_json::json!({"bool": {diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rsindex e26ba4046c..149f2b6431 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs@@ -3,13 +3,16 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::{DefaultSearchResponse, Highlight, parse_highlight_hit},+ model::{+ DefaultSearchResponse, NameIndex, SearchGotoChannel, SearchGotoContent, SearchHit,+ parse_highlight_hit,+ },query::Keys,},};use crate::SearchOn;-use models_opensearch::SearchIndex;+use models_opensearch::{SearchEntityType, SearchIndex};use opensearch_query_builder::{BoolQueryBuilder, FieldSort, QueryType, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,ToOpenSearchJson,@@ -30,21 +33,11 @@ pub(crate) struct ChannelMessageIndex {pub updated_at_seconds: i64,}-#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]-pub struct ChannelMessageSearchResponse {- pub channel_id: String,- pub channel_type: String,- pub org_id: Option<i64>,- pub message_id: String,- pub thread_id: Option<String>,- pub sender_id: String,- pub mentions: Vec<String>,- pub created_at: i64,- pub updated_at: i64,- #[serde(skip_serializing_if = "Option::is_none")]- pub score: Option<f64>,- /// Contains the highlight matches for the channel name and content- pub highlight: Highlight,+#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[serde(untagged)]+pub(crate) enum ChannelMessageNameIndex {+ Name(NameIndex),+ ChannelMessage(ChannelMessageIndex),}#[derive(Default)]@@ -52,9 +45,10 @@ pub(crate) struct ChannelMessageSearchConfig;impl SearchQueryConfig for ChannelMessageSearchConfig {const USER_ID_KEY: &'static str = "sender_id";- const TITLE_KEY: Option<&'static str> = None;+ const TITLE_KEY: &'static str = "name";+ const ENTITY_INDEX: SearchEntityType = SearchEntityType::Channels;- fn default_sort_types() -> Vec<SortType<'static>> {+ fn default_sort_types<'a>() -> Vec<SortType<'a>> {vec![SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),@@ -108,32 +102,42 @@ impl ChannelMessageQueryBuilder {}/// Builds the main bool query for the index- pub fn build_bool_query(&self) -> Result<BoolQueryBuilder<'static>> {- // Build the main bool query containing all terms and any other filters- let mut bool_query = self.inner.build_bool_query()?;+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ let mut content_and_name_bool_queries = self.inner.build_content_and_name_bool_query()?;// CUSTOM ATTRIBUTES SECTION+ if self.inner.search_on == SearchOn::Content+ || self.inner.search_on == SearchOn::NameContent+ {+ let mut bool_query = content_and_name_bool_queries+ .content_bool_query+ .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;- // Add thread_ids to must clause if provided- if !self.thread_ids.is_empty() {- bool_query.must(QueryType::terms("thread_id", self.thread_ids.clone()));- }+ // Add thread_ids to must clause if provided+ if !self.thread_ids.is_empty() {+ bool_query.must(QueryType::terms("thread_id", self.thread_ids.clone()));+ }- // Add mentions to must clause if provided- if !self.mentions.is_empty() {- bool_query.must(QueryType::terms("mentions", self.mentions.clone()));- }+ // Add mentions to must clause if provided+ if !self.mentions.is_empty() {+ bool_query.must(QueryType::terms("mentions", self.mentions.clone()));+ }- // Add sender_ids to must clause if provided- if !self.sender_ids.is_empty() {- bool_query.must(QueryType::terms("sender_id", self.sender_ids.clone()));+ // Add sender_ids to must clause if provided+ if !self.sender_ids.is_empty() {+ bool_query.must(QueryType::terms("sender_id", self.sender_ids.clone()));+ }++ content_and_name_bool_queries.content_bool_query = Some(bool_query);}// END CUSTOM ATTRIBUTES SECTION+ let bool_query = self.inner.build_bool_query(content_and_name_bool_queries)?;+Ok(bool_query)}- fn build_search_request(&self) -> Result<SearchRequest<'static>> {+ fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {let bool_query = self.build_bool_query()?;// Build the search request with the bool query@@ -192,7 +196,7 @@ impl ChannelMessageSearchArgs {pub(crate) async fn search_channel_messages(client: &opensearch::OpenSearch,args: ChannelMessageSearchArgs,-) -> Result<Vec<ChannelMessageSearchResponse>> {+) -> Result<Vec<SearchHit>> {let query_body = args.build()?;let response = client@@ -212,7 +216,7 @@ pub(crate) async fn search_channel_messages(details: e.to_string(),})?;- let result: DefaultSearchResponse<ChannelMessageIndex> = serde_json::from_slice(&bytes)+ let result: DefaultSearchResponse<ChannelMessageNameIndex> = serde_json::from_slice(&bytes).map_err(|e| OpensearchClientError::SearchDeserializationFailed {details: e.to_string(),raw_body: String::from_utf8_lossy(&bytes).to_string(),@@ -222,18 +226,8 @@ pub(crate) async fn search_channel_messages(.hits.hits.into_iter()- .map(|hit| ChannelMessageSearchResponse {- channel_id: hit.source.entity_id,- channel_type: hit.source.channel_type,- org_id: hit.source.org_id,- message_id: hit.source.message_id,- thread_id: hit.source.thread_id,- sender_id: hit.source.sender_id,- mentions: hit.source.mentions,- created_at: hit.source.created_at_seconds,- updated_at: hit.source.updated_at_seconds,- score: hit.score,- highlight: hit+ .map(|hit| {+ let highlight = hit.highlight.map(|h| {parse_highlight_hit(@@ -244,7 +238,30 @@ pub(crate) async fn search_channel_messages(},)})- .unwrap_or_default(),+ .unwrap_or_default();++ match hit.source {+ ChannelMessageNameIndex::Name(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: a.entity_type,+ score: hit.score,+ highlight,+ goto: None,+ },+ ChannelMessageNameIndex::ChannelMessage(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Channels,+ score: hit.score,+ highlight,+ goto: Some(SearchGotoContent::Channels(SearchGotoChannel {+ channel_message_id: a.message_id,+ thread_id: a.thread_id,+ sender_id: a.sender_id,+ created_at: a.created_at_seconds,+ updated_at: a.updated_at_seconds,+ })),+ },+ }}).collect())}diff --git a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs b/rust/cloud-storage/opensearch_client/src/search/channels/test.rsindex bbfa094551..5599702c7d 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels/test.rs@@ -33,6 +33,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"content": "test"}},+ {"term": {"_index": "channels"}},{"terms": {"thread_id": ["thread1", "thread2"]diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rsindex 3d90e3a5ce..c50ce160ec 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs@@ -3,14 +3,17 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::{DefaultSearchResponse, Highlight, parse_highlight_hit},+ model::{+ DefaultSearchResponse, NameIndex, SearchGotoChat, SearchGotoContent, SearchHit,+ parse_highlight_hit,+ },query::Keys,utils::should_wildcard_field_query_builder,},};use crate::SearchOn;-use models_opensearch::SearchIndex;+use models_opensearch::{SearchEntityType, SearchIndex};use opensearch_query_builder::{BoolQueryBuilder, FieldSort, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,ToOpenSearchJson,@@ -28,25 +31,21 @@ pub(crate) struct ChatIndex {pub content: String,}-#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]-pub struct ChatSearchResponse {- pub chat_id: String,- pub chat_message_id: String,- pub user_id: String,- pub role: String,- pub updated_at: i64,- pub title: String,- pub score: Option<f64>,- pub highlight: Highlight,+#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[serde(untagged)]+pub(crate) enum ChatNameIndex {+ Name(NameIndex),+ Chat(ChatIndex),}pub(crate) struct ChatSearchConfig;impl SearchQueryConfig for ChatSearchConfig {const USER_ID_KEY: &'static str = "user_id";- const TITLE_KEY: Option<&'static str> = Some("title");+ const TITLE_KEY: &'static str = "name";+ const ENTITY_INDEX: SearchEntityType = SearchEntityType::Chats;- fn default_sort_types() -> Vec<SortType<'static>> {+ fn default_sort_types<'a>() -> Vec<SortType<'a>> {vec![SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),@@ -87,23 +86,33 @@ impl ChatQueryBuilder {self}- pub fn build_bool_query(&self) -> Result<BoolQueryBuilder<'static>> {- let mut bool_query = self.inner.build_bool_query()?;+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ let mut content_and_name_bool_queries = self.inner.build_content_and_name_bool_query()?;// CUSTOM ATTRIBUTES SECTION-- // If role is provided, add them to the must query- if !self.role.is_empty() {- let should_query = should_wildcard_field_query_builder("role", &self.role);- bool_query.must(should_query);+ if self.inner.search_on == SearchOn::Content+ || self.inner.search_on == SearchOn::NameContent+ {+ let mut bool_query = content_and_name_bool_queries+ .content_bool_query+ .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;++ // Add role to must clause if provided+ if !self.role.is_empty() {+ let should_query = should_wildcard_field_query_builder("role", &self.role);+ bool_query.must(should_query);+ }++ content_and_name_bool_queries.content_bool_query = Some(bool_query);}-// END CUSTOM ATTRIBUTES SECTION+ let bool_query = self.inner.build_bool_query(content_and_name_bool_queries)?;+Ok(bool_query)}- fn build_search_request(&self) -> Result<SearchRequest<'static>> {+ fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {let bool_query = self.build_bool_query()?;// Build the search request with the bool query@@ -157,7 +166,7 @@ impl ChatSearchArgs {pub(crate) async fn search_chats(client: &opensearch::OpenSearch,args: ChatSearchArgs,-) -> Result<Vec<ChatSearchResponse>> {+) -> Result<Vec<SearchHit>> {let query_body = args.build()?;let response = client@@ -177,25 +186,20 @@ pub(crate) async fn search_chats(details: e.to_string(),})?;- let result: DefaultSearchResponse<ChatIndex> = serde_json::from_slice(&bytes).map_err(|e| {- OpensearchClientError::SearchDeserializationFailed {- details: e.to_string(),- raw_body: String::from_utf8_lossy(&bytes).to_string(),- }- })?;+ let result: DefaultSearchResponse<ChatNameIndex> =+ serde_json::from_slice(&bytes).map_err(|e| {+ OpensearchClientError::SearchDeserializationFailed {+ details: e.to_string(),+ raw_body: String::from_utf8_lossy(&bytes).to_string(),+ }+ })?;Ok(result.hits.hits.into_iter()- .map(|hit| ChatSearchResponse {- chat_id: hit.source.entity_id,- chat_message_id: hit.source.chat_message_id,- user_id: hit.source.user_id,- role: hit.source.role,- title: hit.source.title,- score: hit.score,- highlight: hit+ .map(|hit| {+ let highlight = hit.highlight.map(|h| {parse_highlight_hit(@@ -206,8 +210,27 @@ pub(crate) async fn search_chats(},)})- .unwrap_or_default(),- updated_at: hit.source.updated_at_seconds,+ .unwrap_or_default();++ match hit.source {+ ChatNameIndex::Name(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: a.entity_type,+ score: hit.score,+ highlight,+ goto: None,+ },+ ChatNameIndex::Chat(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Chats,+ score: hit.score,+ highlight,+ goto: Some(SearchGotoContent::Chats(SearchGotoChat {+ chat_message_id: a.chat_message_id,+ role: a.role,+ })),+ },+ }}).collect())}diff --git a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs b/rust/cloud-storage/opensearch_client/src/search/chats/test.rsindex ebeb97ef32..eea4c5bd0f 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats/test.rs@@ -31,6 +31,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"content": "test"}},+ {"term": {"_index": "chats"}},{"bool": {"minimum_should_match": 1,diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex b8a9247004..eaa93d55fb 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -3,13 +3,16 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::{DefaultSearchResponse, Highlight, parse_highlight_hit},+ model::{+ DefaultSearchResponse, NameIndex, SearchGotoContent, SearchGotoDocument, SearchHit,+ parse_highlight_hit,+ },query::Keys,},};use crate::SearchOn;-use models_opensearch::SearchIndex;+use models_opensearch::{SearchEntityType, SearchIndex};use opensearch_query_builder::{BoolQueryBuilder, FieldSort, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,ToOpenSearchJson,@@ -21,9 +24,10 @@ pub(crate) struct DocumentSearchConfig;impl SearchQueryConfig for DocumentSearchConfig {const USER_ID_KEY: &'static str = "owner_id";- const TITLE_KEY: Option<&'static str> = Some("document_name");+ const TITLE_KEY: &'static str = "name";+ const ENTITY_INDEX: SearchEntityType = SearchEntityType::Documents;- fn default_sort_types() -> Vec<SortType<'static>> {+ fn default_sort_types<'a>() -> Vec<SortType<'a>> {vec![SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),@@ -56,11 +60,12 @@ impl DocumentQueryBuilder {fn disable_recency(disable_recency: bool) -> Self;}- pub fn build_bool_query(&self) -> Result<BoolQueryBuilder<'static>> {- self.inner.build_bool_query()+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ self.inner+ .build_bool_query(self.inner.build_content_and_name_bool_query()?)}- fn build_search_request(self) -> Result<SearchRequest<'static>> {+ fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is used@@ -84,18 +89,11 @@ pub(crate) struct DocumentIndex {pub updated_at_seconds: i64,}-#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]-pub struct DocumentSearchResponse {- pub document_id: String,- pub document_name: String,- pub node_id: String,- pub owner_id: String,- pub file_type: String,- pub updated_at: i64,- /// Contains the highlight matches for the document name and content- pub highlight: Highlight,- pub raw_content: Option<String>,- pub score: Option<f64>,+#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[serde(untagged)]+pub(crate) enum DocumentNameIndex {+ Name(NameIndex),+ Document(DocumentIndex),}#[derive(Debug)]@@ -138,7 +136,7 @@ impl DocumentSearchArgs {pub(crate) async fn search_documents(client: &opensearch::OpenSearch,args: DocumentSearchArgs,-) -> Result<Vec<DocumentSearchResponse>> {+) -> Result<Vec<SearchHit>> {let query_body = args.build()?;tracing::trace!("query: {}", query_body);@@ -160,7 +158,7 @@ pub(crate) async fn search_documents(details: e.to_string(),})?;- let result: DefaultSearchResponse<DocumentIndex> =+ let result: DefaultSearchResponse<DocumentNameIndex> =serde_json::from_slice(&bytes).map_err(|e| {OpensearchClientError::SearchDeserializationFailed {details: e.to_string(),@@ -172,16 +170,8 @@ pub(crate) async fn search_documents(.hits.hits.into_iter()- .map(|hit| DocumentSearchResponse {- document_id: hit.source.entity_id,- node_id: hit.source.node_id,- document_name: hit.source.document_name,- owner_id: hit.source.owner_id,- file_type: hit.source.file_type,- updated_at: hit.source.updated_at_seconds,- raw_content: hit.source.raw_content,- score: hit.score,- highlight: hit+ .map(|hit| {+ let highlight = hit.highlight.map(|h| {parse_highlight_hit(@@ -192,7 +182,27 @@ pub(crate) async fn search_documents(},)})- .unwrap_or_default(),+ .unwrap_or_default();++ match hit.source {+ DocumentNameIndex::Name(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: a.entity_type,+ score: hit.score,+ highlight,+ goto: None,+ },+ DocumentNameIndex::Document(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Documents,+ score: hit.score,+ highlight,+ goto: Some(SearchGotoContent::Documents(SearchGotoDocument {+ node_id: a.node_id,+ raw_content: a.raw_content,+ })),+ },+ }}).collect())}diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rsindex 3ac5042537..7a6c236743 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs@@ -1,3 +1,5 @@+use crate::search::model::SearchResponse;+use super::*;use opensearch_query_builder::ToOpenSearchJson;@@ -30,6 +32,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"content": "test"}},+ {"term": {"_index": "documents"}},],"should": [{diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 5a6424aa31..0fd64f99e5 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -3,14 +3,14 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::{Highlight, parse_highlight_hit},+ model::{NameIndex, SearchGotoContent, SearchGotoEmail, SearchHit, parse_highlight_hit},query::Keys,utils::should_wildcard_field_query_builder,},};use crate::SearchOn;-use models_opensearch::SearchIndex;+use models_opensearch::{SearchEntityType, SearchIndex};use opensearch_query_builder::{BoolQueryBuilder, FieldSort, QueryType, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,ToOpenSearchJson,@@ -23,9 +23,10 @@ pub(crate) struct EmailSearchConfig;impl SearchQueryConfig for EmailSearchConfig {const USER_ID_KEY: &'static str = "user_id";- const TITLE_KEY: Option<&'static str> = Some("subject");+ const TITLE_KEY: &'static str = "name";+ const ENTITY_INDEX: SearchEntityType = SearchEntityType::Emails;- fn default_sort_types() -> Vec<SortType<'static>> {+ fn default_sort_types<'a>() -> Vec<SortType<'a>> {vec![SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),@@ -97,46 +98,55 @@ impl EmailQueryBuilder {self}- pub fn build_bool_query(&self) -> Result<BoolQueryBuilder<'static>> {- // Build the main bool query containing all terms and any other filters- let mut bool_query = self.inner.build_bool_query()?;+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ let mut content_and_name_bool_queries = self.inner.build_content_and_name_bool_query()?;// CUSTOM ATTRIBUTES SECTION+ if self.inner.search_on == SearchOn::Content+ || self.inner.search_on == SearchOn::NameContent+ {+ let mut bool_query = content_and_name_bool_queries+ .content_bool_query+ .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;++ // If link_ids are provided, add them to the query+ if !self.link_ids.is_empty() {+ bool_query.must(QueryType::terms("link_id", self.link_ids.clone()));+ }- // If link_ids are provided, add them to the query- if !self.link_ids.is_empty() {- bool_query.must(QueryType::terms("link_id", self.link_ids.clone()));- }+ if !self.sender.is_empty() {+ // Create new query for senders+ let senders_query = should_wildcard_field_query_builder("sender", &self.sender);+ bool_query.must(senders_query);+ }- if !self.sender.is_empty() {- // Create new query for senders- let senders_query = should_wildcard_field_query_builder("sender", &self.sender);- bool_query.must(senders_query);- }+ if !self.cc.is_empty() {+ let ccs_query = should_wildcard_field_query_builder("cc", &self.cc);+ bool_query.must(ccs_query);+ }- if !self.cc.is_empty() {- let ccs_query = should_wildcard_field_query_builder("cc", &self.cc);- bool_query.must(ccs_query);- }+ if !self.bcc.is_empty() {+ // Create new query for bccs+ let bccs_query = should_wildcard_field_query_builder("bcc", &self.bcc);+ bool_query.must(bccs_query);+ }- if !self.bcc.is_empty() {- // Create new query for bccs- let bccs_query = should_wildcard_field_query_builder("bcc", &self.bcc);- bool_query.must(bccs_query);- }+ if !self.recipients.is_empty() {+ // Create new query for recipients+ let recipients_query =+ should_wildcard_field_query_builder("recipients", &self.recipients);+ bool_query.must(recipients_query);+ }- if !self.recipients.is_empty() {- // Create new query for recipients- let recipients_query =- should_wildcard_field_query_builder("recipients", &self.recipients);- bool_query.must(recipients_query);+ content_and_name_bool_queries.content_bool_query = Some(bool_query);}// END CUSTOM ATTRIBUTES SECTION+ let bool_query = self.inner.build_bool_query(content_and_name_bool_queries)?;Ok(bool_query)}- fn build_search_request(&self) -> Result<SearchRequest<'static>> {+ fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is used@@ -178,22 +188,11 @@ pub(crate) struct EmailIndex {pub content: String,}-#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]-pub struct EmailSearchResponse {- pub thread_id: String,- pub message_id: String,- pub sender: String,- pub recipients: Vec<String>,- pub cc: Vec<String>,- pub bcc: Vec<String>,- pub labels: Vec<String>,- pub link_id: String,- pub user_id: String,- pub updated_at: i64,- pub sent_at: Option<i64>,- pub subject: Option<String>,- pub score: Option<f64>,- pub highlight: Highlight,+#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[serde(untagged)]+pub(crate) enum EmailNameIndex {+ Email(Box<EmailIndex>),+ Name(NameIndex),}pub struct EmailSearchArgs {@@ -245,7 +244,7 @@ impl EmailSearchArgs {pub(crate) async fn search_emails(client: &opensearch::OpenSearch,args: EmailSearchArgs,-) -> Result<Vec<EmailSearchResponse>> {+) -> Result<Vec<SearchHit>> {let query_body = args.build()?;let response = client@@ -265,7 +264,7 @@ pub(crate) async fn search_emails(details: e.to_string(),})?;- let result: DefaultSearchResponse<EmailIndex> =+ let result: DefaultSearchResponse<EmailNameIndex> =serde_json::from_slice(&bytes).map_err(|e| {OpensearchClientError::SearchDeserializationFailed {details: e.to_string(),@@ -277,21 +276,8 @@ pub(crate) async fn search_emails(.hits.hits.into_iter()- .map(|hit| EmailSearchResponse {- thread_id: hit.source.entity_id,- message_id: hit.source.message_id,- subject: hit.source.subject,- sender: hit.source.sender,- recipients: hit.source.recipients,- cc: hit.source.cc,- bcc: hit.source.bcc,- labels: hit.source.labels,- link_id: hit.source.link_id,- user_id: hit.source.user_id,- updated_at: hit.source.updated_at_seconds,- sent_at: hit.source.sent_at_seconds,- score: hit.score,- highlight: hit+ .map(|hit| {+ let highlight = hit.highlight.map(|h| {parse_highlight_hit(@@ -302,7 +288,32 @@ pub(crate) async fn search_emails(},)})- .unwrap_or_default(),+ .unwrap_or_default();++ match hit.source {+ EmailNameIndex::Name(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: a.entity_type,+ goto: None,+ score: hit.score,+ highlight,+ },+ EmailNameIndex::Email(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Emails,+ score: hit.score,+ highlight,+ goto: Some(SearchGotoContent::Emails(SearchGotoEmail {+ email_message_id: a.message_id,+ bcc: a.bcc,+ cc: a.cc,+ labels: a.labels,+ sent_at: a.sent_at_seconds,+ sender: a.sender,+ recipients: a.recipients,+ })),+ },+ }}).collect())}diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rsindex 8d289065b8..e7ad6154c4 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -36,6 +36,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"content": "test"}},+ {"term": {"_index": "emails"}},{"terms": {"link_id": ["link1", "link2"]diff --git a/rust/cloud-storage/opensearch_client/src/search/model.rs b/rust/cloud-storage/opensearch_client/src/search/model.rsindex d6bfaad537..2dfce6b309 100644--- a/rust/cloud-storage/opensearch_client/src/search/model.rs+++ b/rust/cloud-storage/opensearch_client/src/search/model.rs@@ -1,5 +1,7 @@use std::{collections::HashMap, fmt::Display};+use models_opensearch::SearchEntityType;+use crate::search::query::Keys;/// macro open/close tags for highlight matches@@ -46,17 +48,11 @@ pub(crate) fn parse_highlight_hit(highlight: HashMap<String, Vec<String>>,keys: Keys,) -> Highlight {- let name = if let Some(title_key) = keys.title_key {- highlight- .get(title_key)- .and_then(|v| v.first())- .map(|v| v.to_string())- } else {- None- };-Highlight {- name,+ name: highlight+ .get(keys.title_key)+ .and_then(|v| v.first())+ .map(|v| v.to_string()),content: highlight.get(keys.content_key).map(|v| v.to_vec())@@ -94,3 +90,88 @@ pub(crate) struct SearchResponse<T> {pub timed_out: bool,pub _shards: Shards,}++#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub struct NameIndex {+ /// The entity id+ pub entity_id: String,+ /// The entity type+ pub entity_type: SearchEntityType,+ /// The name of the entity+ pub name: String,+ /// The creator of the entity+ pub user_id: String,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]+pub struct SearchGotoDocument {+ /// The node id of the document.+ /// This is either a 0-indexed page number for pdfs (and docx since they are pdfs)+ /// or a uuid of a lexical node for md. This can be ignored for all other+ /// file types.+ pub node_id: String,+ /// The raw content of the document+ pub raw_content: Option<String>,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]+pub struct SearchGotoChat {+ /// The chat message id+ pub chat_message_id: String,+ /// The role of the chat message+ pub role: String,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]+pub struct SearchGotoEmail {+ /// The email message id+ pub email_message_id: String,+ /// The bcc of the email+ pub bcc: Vec<String>,+ /// The cc of the email+ pub cc: Vec<String>,+ /// The labels of the email+ pub labels: Vec<String>,+ /// The sent_at timestamp of the email+ pub sent_at: Option<i64>,+ /// The sender of the email+ pub sender: String,+ /// The recipients of the email+ pub recipients: Vec<String>,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]+pub struct SearchGotoChannel {+ /// The channel message id+ pub channel_message_id: String,+ pub thread_id: Option<String>,+ pub sender_id: String,+ pub created_at: i64,+ pub updated_at: i64,+}++/// Enum containing structs for all data needed to handle search "goto" in the frontend+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]+#[serde(untagged)]+pub enum SearchGotoContent {+ Documents(SearchGotoDocument),+ Chats(SearchGotoChat),+ Emails(SearchGotoEmail),+ Channels(SearchGotoChannel),+ // there is no goto needed for projects+}++/// This struct represents a single search hit for a given entity+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]+pub struct SearchHit {+ /// The id of the entity+ pub entity_id: String,+ /// The entity type+ pub entity_type: SearchEntityType,+ /// The score of the match+ pub score: Option<f64>,+ /// The highlight of the match+ pub highlight: Highlight,+ /// The goto content for the entity+ pub goto: Option<SearchGotoContent>,+}diff --git a/rust/cloud-storage/opensearch_client/src/search/projects.rs b/rust/cloud-storage/opensearch_client/src/search/projects.rsindex f9205fecee..5575b857eb 100644--- a/rust/cloud-storage/opensearch_client/src/search/projects.rs+++ b/rust/cloud-storage/opensearch_client/src/search/projects.rs@@ -3,13 +3,13 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::{Highlight, MacroEm, SearchResponse, parse_highlight_hit},+ model::{MacroEm, SearchHit, SearchResponse, parse_highlight_hit},query::Keys,},};use crate::SearchOn;-use models_opensearch::SearchIndex;+use models_opensearch::{SearchEntityType, SearchIndex};use opensearch_query_builder::{BoolQueryBuilder, HighlightField, SearchRequest, ToOpenSearchJson};use serde::{Deserialize, Serialize};use serde_json::Value;@@ -19,15 +19,16 @@ pub(crate) struct ProjectSearchConfig;impl SearchQueryConfig for ProjectSearchConfig {const USER_ID_KEY: &'static str = "user_id";- const TITLE_KEY: Option<&'static str> = Some("project_name");+ const TITLE_KEY: &'static str = "project_name";+ const ENTITY_INDEX: SearchEntityType = SearchEntityType::Projects;// Projects have no "content" to highlight match on, so match on the TITLE_KEY instead- fn default_highlight() -> opensearch_query_builder::Highlight<'static> {+ fn default_highlight<'a>() -> opensearch_query_builder::Highlight<'a> {opensearch_query_builder::Highlight::new().require_field_match(true).field(// we know the title key exists because it's implemented right above- Self::TITLE_KEY.unwrap(),+ Self::TITLE_KEY,HighlightField::new().highlight_type("plain").number_of_fragments(1)@@ -62,11 +63,12 @@ impl ProjectQueryBuilder {fn disable_recency(disable_recency: bool) -> Self;}- pub fn build_bool_query(&self) -> Result<BoolQueryBuilder<'static>> {- self.inner.build_bool_query()+ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ self.inner+ .build_bool_query(self.inner.build_content_and_name_bool_query()?)}- fn build_search_request(&self) -> Result<SearchRequest<'static>> {+ fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is used@@ -124,22 +126,11 @@ impl ProjectSearchArgs {}}-#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct ProjectSearchResponse {- pub project_id: String,- pub user_id: String,- pub project_name: String,- pub created_at: i64,- pub updated_at: i64,- pub score: Option<f64>,- pub highlight: Highlight,-}-#[tracing::instrument(skip(client, args), err)]pub(crate) async fn search_projects(client: &opensearch::OpenSearch,args: ProjectSearchArgs,-) -> Result<Vec<ProjectSearchResponse>> {+) -> Result<Vec<SearchHit>> {let query_body = args.build()?;let response = client@@ -170,12 +161,9 @@ pub(crate) async fn search_projects(.hits.hits.into_iter()- .map(|hit| ProjectSearchResponse {- project_id: hit.source.entity_id,- user_id: hit.source.user_id,- project_name: hit.source.project_name,- created_at: hit.source.created_at_seconds,- updated_at: hit.source.updated_at_seconds,+ .map(|hit| SearchHit {+ entity_id: hit.source.entity_id,+ entity_type: SearchEntityType::Projects,score: hit.score,highlight: hit.highlight@@ -189,6 +177,7 @@ pub(crate) async fn search_projects()}).unwrap_or_default(),+ goto: None,}).collect())}diff --git a/rust/cloud-storage/opensearch_client/src/search/projects/test.rs b/rust/cloud-storage/opensearch_client/src/search/projects/test.rsindex bc7052e76c..0b8273a80d 100644--- a/rust/cloud-storage/opensearch_client/src/search/projects/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/projects/test.rs@@ -30,6 +30,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"project_name": "test"}},+ {"term": {"_index": "projects"}},],"should": [{diff --git a/rust/cloud-storage/opensearch_client/src/search/query.rs b/rust/cloud-storage/opensearch_client/src/search/query.rsindex 795dff60e2..8f5e6f8064 100644--- a/rust/cloud-storage/opensearch_client/src/search/query.rs+++ b/rust/cloud-storage/opensearch_client/src/search/query.rs@@ -1,6 +1,8 @@//! This module contains the logic for generating queries using terms-use crate::{Result, error::OpensearchClientError};+use std::borrow::Cow;++use crate::{Result, error::OpensearchClientError, search_on::NameOrContent};use opensearch_query_builder::*;use unicode_segmentation::UnicodeSegmentation;@@ -8,7 +10,7 @@ use unicode_segmentation::UnicodeSegmentation;/// Containing keys for the title and content fieldspub struct Keys<'a> {/// The title field key- pub title_key: Option<&'a str>,+ pub title_key: &'a str,/// The content field keypub content_key: &'a str,}@@ -29,29 +31,67 @@ fn validate_last_term_length(term: &str) -> bool {UnicodeSegmentation::graphemes(term, true).count() >= 3}-impl QueryKey {- /// Creates a query key given a match type- pub fn from_match_type(match_type: &str) -> Result<Self> {- match match_type {- "exact" => Ok(Self::MatchPhrase),- "partial" => Ok(Self::MatchPhrasePrefix),- "regexp" => Ok(Self::Regexp),- _ => Err(OpensearchClientError::InvalidMatchType {- match_type: match_type.to_string(),- }),+pub(crate) struct CreateQueryParams<'a> {+ /// The query key to use+ /// This is only used if unified params are not provided+ pub query_key: QueryKey,+ /// The field to search on+ pub field: &'a str,+ /// The term to search for+ pub term: &'a str,+ /// Optional unified search params+ /// If present, the unified search field is used+ pub unified_params: Option<&'a CreateQueryUnifiedParams>,+}++pub(crate) struct CreateQueryUnifiedParams {+ /// Specifies whether the unified search field is a name or content field+ /// This is used to determine the boosting of the match queries+ pub name_or_content: NameOrContent,+}++/// Creates a query for a given term+pub(crate) fn create_query<'a>(params: CreateQueryParams<'a>) -> QueryType<'a> {+ let CreateQueryParams {+ query_key,+ field,+ term,+ unified_params,+ } = params;++ if let Some(unified_params) = unified_params {+ let name_or_content = unified_params.name_or_content;+ // base bool query+ let mut bool_query = BoolQueryBuilder::new();+ bool_query.minimum_should_match(1);++ let mut match_phrase_prefix_query = MatchPhrasePrefixQuery::new(field.to_string(), term);+ let mut match_query = MatchQuery::new(field.to_string(), term);++ match name_or_content {+ NameOrContent::Name => {+ match_phrase_prefix_query = match_phrase_prefix_query.boost(1000.0);+ match_query = match_query.boost(0.1).minimum_should_match("80%");+ }+ NameOrContent::Content => {+ match_phrase_prefix_query = match_phrase_prefix_query.boost(900.0);+ match_query = match_query+ .boost(0.09)+ .minimum_should_match(term.split(' ').count().to_string());+ }}- }- /// Creates a query given a field and term- pub fn create_query(&self, field: &str, term: &str) -> QueryType<'static> {+ bool_query.should(match_phrase_prefix_query.into());+ bool_query.should(match_query.into());++ bool_query.build().into()+ } else {// Fixes https://linear.app/macro-eng/issue/M-5094/unified-search-match-prefix-on-phrase-should-not-constrain-terms// We need to create a more complex combo query if the last word in a term is less than 3 characters.let mut terms = term.split(' ').collect::<Vec<_>>();let last_term = terms.last().unwrap_or(&"");let is_last_term_long_enough = validate_last_term_length(last_term);- // TODO: we need type validation that the term is not an empty string- // As a workaround, we will check if last_term is empty before entering into this blockif !last_term.is_empty() && !is_last_term_long_enough && terms.len() > 1 {tracing::trace!("last value in term has length less than 3, building combo query");@@ -60,15 +100,15 @@ impl QueryKey {let wildcard_pattern = format!("*{}*", last_part_of_term.to_lowercase());// build the first term query- let first_term_query = match self {- Self::MatchPhrase => QueryType::MatchPhrase(MatchPhraseQuery::new(+ let first_term_query = match query_key {+ QueryKey::MatchPhrase => QueryType::MatchPhrase(MatchPhraseQuery::new(field.to_string(),first_part_of_term,)),- Self::MatchPhrasePrefix => QueryType::MatchPhrasePrefix(+ QueryKey::MatchPhrasePrefix => QueryType::MatchPhrasePrefix(MatchPhrasePrefixQuery::new(field.to_string(), first_part_of_term),),- Self::Regexp => {+ QueryKey::Regexp => {QueryType::Regexp(RegexpQuery::new(field.to_string(), first_part_of_term))}};@@ -87,38 +127,57 @@ impl QueryKey {return bool_query.build().into();}- match self {- Self::MatchPhrase => {+ match query_key {+ QueryKey::MatchPhrase => {QueryType::MatchPhrase(MatchPhraseQuery::new(field.to_string(), term.to_string()))}- Self::MatchPhrasePrefix => QueryType::MatchPhrasePrefix(MatchPhrasePrefixQuery::new(- field.to_string(),- term.to_string(),- )),- Self::Regexp => {+ QueryKey::MatchPhrasePrefix => QueryType::MatchPhrasePrefix(+ MatchPhrasePrefixQuery::new(field.to_string(), term.to_string()),+ ),+ QueryKey::Regexp => {QueryType::Regexp(RegexpQuery::new(field.to_string(), term.to_string()))}}}}+impl QueryKey {+ /// Creates a query key given a match type+ pub fn from_match_type(match_type: &str) -> Result<Self> {+ match match_type {+ "exact" => Ok(Self::MatchPhrase),+ "partial" => Ok(Self::MatchPhrasePrefix),+ "regexp" => Ok(Self::Regexp),+ _ => Err(OpensearchClientError::InvalidMatchType {+ match_type: match_type.to_string(),+ }),+ }+ }+}+/// Generate the terms for the "must" query-pub(crate) fn generate_terms_must_query(+pub(crate) fn generate_terms_must_query<'a>(query_key: QueryKey,- fields: &[&str],- terms: &[String],-) -> QueryType<'static> {+ field: &'a str,+ terms: impl Into<Cow<'a, [&'a str]>>,+ unified_params: Option<&'a CreateQueryUnifiedParams>,+) -> QueryType<'a> {let mut terms_must_query = BoolQueryBuilder::new();terms_must_query.minimum_should_match(1);+ let terms = terms.into();+// Map terms to queries- let queries: Vec<_> = fields+ let queries: Vec<_> = terms.iter()- .flat_map(|field| {- terms- .iter()- .map(|term| query_key.create_query(field, term.as_str()))+ .map(|term| {+ create_query(CreateQueryParams {+ query_key,+ field,+ term,+ unified_params,+ })}).collect();@@ -137,62 +196,5 @@ pub(crate) fn generate_terms_must_query(terms_must_query.build().into()}-/// Generates the term queries SearchOn::NameContent-pub(crate) fn generate_name_content_query(keys: &Keys, terms: &[String]) -> QueryType<'static> {- let mut terms_must_query = BoolQueryBuilder::new();-- terms_must_query.minimum_should_match(1);-- let queries: Vec<QueryType> = terms- .iter()- .map(|term| {- // base bool query- let mut bool_query = BoolQueryBuilder::new();- bool_query.minimum_should_match(1);-- if let Some(title_key) = keys.title_key {- bool_query.should(QueryType::MatchPhrasePrefix(- MatchPhrasePrefixQuery::new(title_key.to_string(), term.clone()).boost(1000.0),- ));- }-- bool_query.should(QueryType::MatchPhrasePrefix(- MatchPhrasePrefixQuery::new(keys.content_key.to_string(), term.clone())- .boost(900.0),- ));-- if let Some(title_key) = keys.title_key {- bool_query.should(QueryType::Match(- MatchQuery::new(title_key.to_string(), term.clone())- .boost(0.1)- .minimum_should_match("80%"), // TODO: we may need to play around with this to get the best highlight match- ));- }-- bool_query.should(QueryType::Match(- MatchQuery::new(keys.content_key.to_string(), term.clone())- .boost(0.09)- .minimum_should_match(term.split(' ').count().to_string()), // TODO: we may need to play around with this to get the best highlight match- ));-- bool_query.build().into()- })- .collect();-- // If we only have 1 query created, we can just return that singular query to be added to the- // main bool must query- if queries.len() == 1 {- return queries[0].clone();- }-- // Otherwise, we need to add all the queries to a new bool should in order to properly search- // over multiple terms- for query in queries {- terms_must_query.should(query);- }-- terms_must_query.build().into()-}-#[cfg(test)]mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/query/test.rs b/rust/cloud-storage/opensearch_client/src/search/query/test.rsindex 3dd3f13afc..1a8fe4b3d8 100644--- a/rust/cloud-storage/opensearch_client/src/search/query/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/query/test.rs@@ -35,7 +35,13 @@ fn test_query_key_create_query() -> anyhow::Result<()> {}});- let result = query_key.create_query(field, term).to_json();+ let result = create_query(CreateQueryParams {+ query_key,+ field,+ term,+ unified_params: None,+ })+ .to_json();assert_eq!(result, expected);@@ -69,9 +75,13 @@ fn test_query_key_short_last_word() -> anyhow::Result<()> {}});- let result = QueryKey::MatchPhrasePrefix- .create_query(field, term)- .to_json();+ let result = create_query(CreateQueryParams {+ query_key: QueryKey::MatchPhrasePrefix,+ field,+ term,+ unified_params: None,+ })+ .to_json();assert_eq!(result, expected);@@ -80,7 +90,9 @@ fn test_query_key_short_last_word() -> anyhow::Result<()> {#[test]fn test_generate_terms_must_query() -> anyhow::Result<()> {- let result = generate_terms_must_query(QueryKey::MatchPhrase, &["test"], &["test".to_string()]);+ let terms: Cow<'_, [&str]> = Cow::Borrowed(&["test"]);++ let result = generate_terms_must_query(QueryKey::MatchPhrase, "test", terms, None);let expected = serde_json::json!({"match_phrase": {@@ -90,11 +102,8 @@ fn test_generate_terms_must_query() -> anyhow::Result<()> {assert_eq!(result.to_json(), expected);- let result = generate_terms_must_query(- QueryKey::MatchPhrasePrefix,- &["test"],- &["test".to_string(), "test2".to_string()],- );+ let terms: Cow<'_, [&str]> = Cow::Borrowed(&["test", "test2"]);+ let result = generate_terms_must_query(QueryKey::MatchPhrasePrefix, "test", terms, None);let expected = serde_json::json!({"bool": {@@ -124,13 +133,10 @@ fn test_generate_terms_must_query() -> anyhow::Result<()> {}#[test]-fn test_generate_name_content_query() -> anyhow::Result<()> {- let keys = Keys {- title_key: Some("test_title"),- content_key: "test_content",- };-- let result = generate_name_content_query(&keys, &["test".to_string()]);+fn test_create_query_unified_name() -> anyhow::Result<()> {+ let field = "test";+ let term = "test";+ let query_key = QueryKey::MatchPhrase;let expected = serde_json::json!({"bool": {@@ -138,144 +144,45 @@ fn test_generate_name_content_query() -> anyhow::Result<()> {"should": [{"match_phrase_prefix": {- "test_title": {+ "test": {"query": "test","boost": 1000.0}}},- {- "match_phrase_prefix": {- "test_content": {- "query": "test",- "boost": 900.0- }- }- },{"match": {- "test_title": {+ "test": {"boost": 0.1,"minimum_should_match": "80%","query": "test"}}- },- {- "match": {- "test_content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }}]}});- assert_eq!(result.to_json(), expected);-- let result = generate_name_content_query(&keys, &["test".to_string(), "test2".to_string()]);-- let expected = serde_json::json!({- "bool": {- "minimum_should_match": 1,- "should": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "test_title": {- "boost": 1000.0,- "query": "test"- }- }- },- {- "match_phrase_prefix": {- "test_content": {- "boost": 900.0,- "query": "test"- }- }- },- {- "match": {- "test_title": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test"- }- }- },- {- "match": {- "test_content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "test_title": {- "boost": 1000.0,- "query": "test2"- }- }- },- {- "match_phrase_prefix": {- "test_content": {- "boost": 900.0,- "query": "test2"- }- }- },- {- "match": {- "test_title": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test2"- }- }- },- {- "match": {- "test_content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test2"- }- }- }- ]- }- }- ]- }- });+ let result = create_query(CreateQueryParams {+ query_key,+ field,+ term,+ unified_params: Some(&CreateQueryUnifiedParams {+ name_or_content: NameOrContent::Name,+ }),+ })+ .to_json();- assert_eq!(result.to_json(), expected);+ assert_eq!(result, expected);- let keys = Keys {- title_key: None,- content_key: "test_content",- };+ Ok(())+}- let result = generate_name_content_query(&keys, &["test".to_string()]);+#[test]+fn test_create_query_unified_content() -> anyhow::Result<()> {+ let field = "test";+ let term = "test";+ let query_key = QueryKey::MatchPhrase;let expected = serde_json::json!({"bool": {@@ -283,7 +190,7 @@ fn test_generate_name_content_query() -> anyhow::Result<()> {"should": [{"match_phrase_prefix": {- "test_content": {+ "test": {"query": "test","boost": 900.0}@@ -291,7 +198,7 @@ fn test_generate_name_content_query() -> anyhow::Result<()> {},{"match": {- "test_content": {+ "test": {"boost": 0.09,"minimum_should_match": "1","query": "test"@@ -302,7 +209,17 @@ fn test_generate_name_content_query() -> anyhow::Result<()> {}});- assert_eq!(result.to_json(), expected);+ let result = create_query(CreateQueryParams {+ query_key,+ field,+ term,+ unified_params: Some(&CreateQueryUnifiedParams {+ name_or_content: NameOrContent::Content,+ }),+ })+ .to_json();++ assert_eq!(result, expected);Ok(())}diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex c6511df682..76f7902af2 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -7,29 +7,24 @@ use crate::{builder::SearchQueryConfig,channels::{ChannelMessageIndex, ChannelMessageQueryBuilder, ChannelMessageSearchArgs,- ChannelMessageSearchConfig, ChannelMessageSearchResponse,- },- chats::{- ChatIndex, ChatQueryBuilder, ChatSearchArgs, ChatSearchConfig, ChatSearchResponse,+ ChannelMessageSearchConfig,},+ chats::{ChatIndex, ChatQueryBuilder, ChatSearchArgs, ChatSearchConfig},documents::{DocumentIndex, DocumentQueryBuilder, DocumentSearchArgs, DocumentSearchConfig,- DocumentSearchResponse,- },- emails::{- EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig, EmailSearchResponse,},- model::{DefaultSearchResponse, Hit, MacroEm, parse_highlight_hit},- projects::{- ProjectIndex, ProjectQueryBuilder, ProjectSearchArgs, ProjectSearchConfig,- ProjectSearchResponse,+ emails::{EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig},+ model::{+ DefaultSearchResponse, Hit, MacroEm, NameIndex, SearchGotoChannel, SearchGotoChat,+ SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit, parse_highlight_hit,},+ projects::{ProjectIndex, ProjectQueryBuilder, ProjectSearchArgs, ProjectSearchConfig},query::Keys,},};use crate::SearchOn;-use models_opensearch::{SearchEntityType, SearchIndex};+use models_opensearch::SearchEntityType;use opensearch_query_builder::*;#[derive(Debug, Default, Clone)]@@ -196,52 +191,44 @@ pub(crate) enum UnifiedSearchIndex {Chat(ChatIndex),Email(EmailIndex),Project(ProjectIndex),-}--#[derive(Debug)]-pub enum UnifiedSearchResponse {- ChannelMessage(ChannelMessageSearchResponse),- Chat(ChatSearchResponse),- Document(DocumentSearchResponse),- Email(EmailSearchResponse),- Project(ProjectSearchResponse),+ Name(NameIndex),}pub struct SplitUnifiedSearchResponseValues {- pub channel_message: Vec<ChannelMessageSearchResponse>,- pub chat: Vec<ChatSearchResponse>,- pub document: Vec<DocumentSearchResponse>,- pub email: Vec<EmailSearchResponse>,- pub project: Vec<ProjectSearchResponse>,+ pub channel_message: Vec<SearchHit>,+ pub chat: Vec<SearchHit>,+ pub document: Vec<SearchHit>,+ pub email: Vec<SearchHit>,+ pub project: Vec<SearchHit>,}-pub trait SplitUnifiedSearchResponse: Iterator<Item = UnifiedSearchResponse> {+pub trait SplitUnifiedSearchResponse: Iterator<Item = SearchHit> {fn split_search_response(self) -> SplitUnifiedSearchResponseValues;}impl<T> SplitUnifiedSearchResponse for Twhere- T: Iterator<Item = UnifiedSearchResponse>,+ T: Iterator<Item = SearchHit>,{fn split_search_response(self) -> SplitUnifiedSearchResponseValues {let (channel_message, chat, document, email, project) = self.into_iter().fold((vec![], vec![], vec![], vec![], vec![]),|(mut channel_message, mut chat, mut document, mut email, mut project), item| {- match item {- UnifiedSearchResponse::ChannelMessage(a) => {- channel_message.push(a);+ match item.entity_type {+ SearchEntityType::Channels => {+ channel_message.push(item);}- UnifiedSearchResponse::Chat(a) => {- chat.push(a);+ SearchEntityType::Chats => {+ chat.push(item);}- UnifiedSearchResponse::Document(a) => {- document.push(a);+ SearchEntityType::Documents => {+ document.push(item);}- UnifiedSearchResponse::Email(a) => {- email.push(a);+ SearchEntityType::Emails => {+ email.push(item);}- UnifiedSearchResponse::Project(a) => {- project.push(a);+ SearchEntityType::Projects => {+ project.push(item);}}(channel_message, chat, document, email, project)@@ -258,72 +245,57 @@ where}}-impl From<Hit<UnifiedSearchIndex>> for UnifiedSearchResponse {+impl From<Hit<UnifiedSearchIndex>> for SearchHit {fn from(index: Hit<UnifiedSearchIndex>) -> Self {match index.source {- UnifiedSearchIndex::ChannelMessage(a) => {- UnifiedSearchResponse::ChannelMessage(ChannelMessageSearchResponse {- channel_id: a.entity_id,- channel_type: a.channel_type,- org_id: a.org_id,- message_id: a.message_id,+ UnifiedSearchIndex::ChannelMessage(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Channels,+ score: index.score,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ChannelMessageSearchConfig::TITLE_KEY,+ content_key: ChannelMessageSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ goto: Some(SearchGotoContent::Channels(SearchGotoChannel {+ channel_message_id: a.message_id,thread_id: a.thread_id,sender_id: a.sender_id,- mentions: a.mentions,created_at: a.created_at_seconds,updated_at: a.updated_at_seconds,- score: index.score,- highlight: index- .highlight- .map(|h| {- parse_highlight_hit(- h,- Keys {- title_key: ChannelMessageSearchConfig::TITLE_KEY,- content_key: ChannelMessageSearchConfig::CONTENT_KEY,- },- )- })- .unwrap_or_default(),- })- }- UnifiedSearchIndex::Document(a) => {- UnifiedSearchResponse::Document(DocumentSearchResponse {- document_id: a.entity_id,- document_name: a.document_name,+ })),+ },+ UnifiedSearchIndex::Document(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Documents,+ score: index.score,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: DocumentSearchConfig::TITLE_KEY,+ content_key: DocumentSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ goto: Some(SearchGotoContent::Documents(SearchGotoDocument {node_id: a.node_id,raw_content: a.raw_content,- owner_id: a.owner_id,- file_type: a.file_type,- updated_at: a.updated_at_seconds,- score: index.score,- highlight: index- .highlight- .map(|h| {- parse_highlight_hit(- h,- Keys {- title_key: DocumentSearchConfig::TITLE_KEY,- content_key: DocumentSearchConfig::CONTENT_KEY,- },- )- })- .unwrap_or_default(),- })- }- UnifiedSearchIndex::Email(a) => UnifiedSearchResponse::Email(EmailSearchResponse {- thread_id: a.entity_id,- message_id: a.message_id,- subject: a.subject,- sender: a.sender,- recipients: a.recipients,- cc: a.cc,- bcc: a.bcc,- labels: a.labels,- link_id: a.link_id,- user_id: a.user_id,- updated_at: a.updated_at_seconds,- sent_at: a.sent_at_seconds,+ })),+ },+ UnifiedSearchIndex::Email(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Emails,score: index.score,highlight: index.highlight@@ -337,35 +309,37 @@ impl From<Hit<UnifiedSearchIndex>> for UnifiedSearchResponse {)}).unwrap_or_default(),- }),- UnifiedSearchIndex::Project(a) => {- UnifiedSearchResponse::Project(ProjectSearchResponse {- project_id: a.entity_id,- user_id: a.user_id,- project_name: a.project_name,- created_at: a.created_at_seconds,- updated_at: a.updated_at_seconds,- score: index.score,- highlight: index- .highlight- .map(|h| {- parse_highlight_hit(- h,- Keys {- title_key: ProjectSearchConfig::TITLE_KEY,- content_key: ProjectSearchConfig::CONTENT_KEY,- },- )- })- .unwrap_or_default(),- })- }- UnifiedSearchIndex::Chat(a) => UnifiedSearchResponse::Chat(ChatSearchResponse {- chat_id: a.entity_id,- chat_message_id: a.chat_message_id,- user_id: a.user_id,- role: a.role,- title: a.title,+ goto: Some(SearchGotoContent::Emails(SearchGotoEmail {+ email_message_id: a.message_id,+ bcc: a.bcc,+ cc: a.cc,+ labels: a.labels,+ sent_at: a.sent_at_seconds,+ sender: a.sender,+ recipients: a.recipients,+ })),+ },+ UnifiedSearchIndex::Project(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Projects,+ score: index.score,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ProjectSearchConfig::TITLE_KEY,+ content_key: ProjectSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ goto: None,+ },+ UnifiedSearchIndex::Chat(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::Chats,score: index.score,highlight: index.highlight@@ -379,8 +353,29 @@ impl From<Hit<UnifiedSearchIndex>> for UnifiedSearchResponse {)}).unwrap_or_default(),- updated_at: a.updated_at_seconds,- }),+ goto: Some(SearchGotoContent::Chats(SearchGotoChat {+ chat_message_id: a.chat_message_id,+ role: a.role,+ })),+ },+ UnifiedSearchIndex::Name(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: a.entity_type,+ score: index.score,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: "name",+ content_key: "",+ },+ )+ })+ .unwrap_or_default(),+ goto: None,+ },}}}@@ -391,18 +386,18 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequesreturn Err(OpensearchClientError::EmptySearchIndices);}// Build out the title keys that we could need for highlighting- let mut title_keys: Vec<Option<&'static str>> = vec![];+ let mut title_keys: HashSet<&'static str> = HashSet::new();for index in &args.search_indices {match index {- SearchEntityType::Channels => title_keys.push(ChannelMessageSearchConfig::TITLE_KEY),- SearchEntityType::Chats => title_keys.push(ChatSearchConfig::TITLE_KEY),- SearchEntityType::Documents => title_keys.push(DocumentSearchConfig::TITLE_KEY),- SearchEntityType::Emails => title_keys.push(EmailSearchConfig::TITLE_KEY),- SearchEntityType::Projects => title_keys.push(ProjectSearchConfig::TITLE_KEY),- }+ SearchEntityType::Channels => title_keys.insert(ChannelMessageSearchConfig::TITLE_KEY),+ SearchEntityType::Chats => title_keys.insert(ChatSearchConfig::TITLE_KEY),+ SearchEntityType::Documents => title_keys.insert(DocumentSearchConfig::TITLE_KEY),+ SearchEntityType::Emails => title_keys.insert(EmailSearchConfig::TITLE_KEY),+ SearchEntityType::Projects => title_keys.insert(ProjectSearchConfig::TITLE_KEY),+ };}- let title_keys: Vec<&'static str> = title_keys.into_iter().flatten().collect();+ let title_keys: Vec<&'static str> = title_keys.into_iter().collect();let mut bool_query = BoolQueryBuilder::new();bool_query.minimum_should_match(1);@@ -410,17 +405,17 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequesif args.search_indices.contains(&SearchEntityType::Documents) {let document_search_args: DocumentSearchArgs = args.clone().into();let document_query_builder: DocumentQueryBuilder = document_search_args.into();- let mut document_bool_query = document_query_builder.build_bool_query()?;- document_bool_query.must(QueryType::term("_index", SearchIndex::Documents.as_ref()));- bool_query.should(document_bool_query.build().into());+ let document_bool_query = document_query_builder.build_bool_query()?;+ let query_type: QueryType = document_bool_query.build().into();+ bool_query.should(query_type.to_owned());}if args.search_indices.contains(&SearchEntityType::Emails) {let email_search_args: EmailSearchArgs = args.clone().into();let email_query_builder: EmailQueryBuilder = email_search_args.into();- let mut email_bool_query = email_query_builder.build_bool_query()?;- email_bool_query.must(QueryType::term("_index", SearchIndex::Emails.as_ref()));- bool_query.should(email_bool_query.build().into());+ let email_bool_query = email_query_builder.build_bool_query()?;+ let query_type: QueryType = email_bool_query.build().into();+ bool_query.should(query_type.to_owned());}// We can only search over channels if we are not explicitly searching by name@@ -429,25 +424,27 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequeslet channel_message_search_args: ChannelMessageSearchArgs = args.clone().into();let channel_message_query_builder: ChannelMessageQueryBuilder =channel_message_search_args.into();- let mut channel_message_bool_query = channel_message_query_builder.build_bool_query()?;- channel_message_bool_query.must(QueryType::term("_index", SearchIndex::Channels.as_ref()));- bool_query.should(channel_message_bool_query.build().into());+ let channel_message_bool_query = channel_message_query_builder.build_bool_query()?;+ let query_type: QueryType = channel_message_bool_query.build().into();+ bool_query.should(query_type.to_owned());}if args.search_indices.contains(&SearchEntityType::Chats) {let chat_search_args: ChatSearchArgs = args.clone().into();let chat_query_builder: ChatQueryBuilder = chat_search_args.into();- let mut chat_bool_query = chat_query_builder.build_bool_query()?;- chat_bool_query.must(QueryType::term("_index", SearchIndex::Chats.as_ref()));- bool_query.should(chat_bool_query.build().into());+ let chat_bool_query = chat_query_builder.build_bool_query()?;+ let query_type: QueryType = chat_bool_query.build().into();+ bool_query.should(query_type.to_owned());}- if args.search_indices.contains(&SearchEntityType::Projects) {+ if args.search_indices.contains(&SearchEntityType::Projects)+ && args.search_on != SearchOn::Content+ {let project_search_args: ProjectSearchArgs = args.clone().into();let project_query_builder: ProjectQueryBuilder = project_search_args.into();- let mut project_bool_query = project_query_builder.build_bool_query()?;- project_bool_query.must(QueryType::term("_index", SearchIndex::Projects.as_ref()));- bool_query.should(project_bool_query.build().into());+ let project_bool_query = project_query_builder.build_bool_query()?;+ let query_type: QueryType = project_bool_query.build().into();+ bool_query.should(query_type.to_owned());}// create the search request@@ -456,23 +453,14 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequessearch_request_builder.from(args.page * args.page_size);search_request_builder.size(args.page_size);- if args.collapse || args.search_on == SearchOn::NameContent || args.search_on == SearchOn::Name- {+ if args.collapse {search_request_builder.collapse(Collapse::new("entity_id"));}- if args.search_on == SearchOn::NameContent {- search_request_builder.track_total_hits(true);- search_request_builder.add_agg(- "total_uniques",- AggregationType::Cardinality(CardinalityAggregation::new("entity_id")),- );- }-// Build sortlet sort = vec![SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),- SortType::Field(FieldSort::new("entity_id", SortOrder::Asc)),+ SortType::Field(FieldSort::new("entity_id", SortOrder::Desc)),];for sort in sort {@@ -539,35 +527,7 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequeslet query_object = bool_query.build();- let built_query: QueryType = match args.search_on {- SearchOn::Name | SearchOn::Content => query_object.into(),- SearchOn::NameContent => {- if args.disable_recency {- query_object.into()- } else {- let mut function_score_query = FunctionScoreQueryBuilder::new();-- function_score_query.query(query_object.into());-- function_score_query.function(ScoreFunction {- function: ScoreFunctionType::Gauss(DecayFunction {- field: "updated_at_seconds".into(),- origin: Some("now".into()),- scale: "21d".into(),- offset: Some("3d".into()),- decay: Some(0.5),- }),- filter: None,- weight: Some(1.3),- });-- function_score_query.boost_mode(BoostMode::Multiply);- function_score_query.score_mode(ScoreMode::Multiply);-- function_score_query.build().into()- }- }- };+ let built_query: QueryType = query_object.into();search_request_builder.query(built_query);@@ -578,7 +538,7 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequespub(crate) async fn search_unified(client: &opensearch::OpenSearch,args: UnifiedSearchArgs,-) -> Result<Vec<UnifiedSearchResponse>> {+) -> Result<Vec<SearchHit>> {let search_request = build_unified_search_request(&args)?.to_json();let search_indices: Vec<&str> = args.search_indices.iter().map(|i| i.as_ref()).collect();diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rsindex d691d71f0d..8c7ea59555 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs@@ -449,7 +449,8 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {let result = build_unified_search_request(&unified_search_args)?;- let expected = serde_json::json!({+ let expected = serde_json::json!(+ {"collapse": {"field": "entity_id"},@@ -514,6 +515,11 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {"content": "test"}},+ {+ "term": {+ "_index": "emails"+ }+ },{"terms": {"link_id": [@@ -613,11 +619,6 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {}]}- },- {- "term": {- "_index": "emails"- }}],"should": [@@ -646,6 +647,11 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {"content": "test"}},+ {+ "term": {+ "_index": "channels"+ }+ },{"terms": {"thread_id": [@@ -669,11 +675,6 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {"id2"]}- },- {- "term": {- "_index": "channels"- }}],"should": [@@ -684,7 +685,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {"id2"]}- },+ }]}},@@ -697,6 +698,11 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {"content": "test"}},+ {+ "term": {+ "_index": "chats"+ }+ },{"bool": {"minimum_should_match": 1,@@ -719,11 +725,6 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {}]}- },- {- "term": {- "_index": "chats"- }}],"should": [@@ -743,38 +744,6 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {]}},- {- "bool": {- "minimum_should_match": 1,- "must": [- {- "match_phrase": {- "content": "test"- }- },- {- "term": {- "_index": "projects"- }- }- ],- "should": [- {- "terms": {- "entity_id": [- "id1",- "id2"- ]- }- },- {- "term": {- "user_id": "user"- }- }- ]- }- }]}},@@ -784,7 +753,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {"_score": "desc"},{- "entity_id": "asc"+ "entity_id": "desc"}]});@@ -845,53 +814,34 @@ fn test_build_unified_search_request_name() -> anyhow::Result<()> {let result = build_unified_search_request(&unified_search_args)?;- let expected = serde_json::json!({+ let expected = serde_json::json!(+ {"collapse": {"field": "entity_id"},"from": 20,"highlight": {"fields": {- "document_name": {- "number_of_fragments": 1,- "post_tags": [- "</macro_em>"- ],- "pre_tags": [- "<macro_em>"- ],- "type": "plain"- },- "subject": {- "number_of_fragments": 1,- "post_tags": [- "</macro_em>"- ],- "pre_tags": [- "<macro_em>"- ],- "type": "plain"- },- "title": {- "number_of_fragments": 1,- "post_tags": [- "</macro_em>"- ],- "pre_tags": [- "<macro_em>"- ],- "type": "plain"- },- "project_name": {- "number_of_fragments": 1,- "post_tags": [- "</macro_em>"- ],- "pre_tags": [- "<macro_em>"- ],- "type": "plain"- }+ "name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "project_name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ }},"require_field_match": true},@@ -905,12 +855,17 @@ fn test_build_unified_search_request_name() -> anyhow::Result<()> {"must": [{"match_phrase": {- "document_name": "test"+ "name": "test"}},{"term": {- "_index": "documents"+ "_index": "names"+ }+ },+ {+ "term": {+ "entity_type": "documents"}}],@@ -925,7 +880,7 @@ fn test_build_unified_search_request_name() -> anyhow::Result<()> {},{"term": {- "owner_id": "user"+ "user_id": "user"}}]@@ -937,112 +892,17 @@ fn test_build_unified_search_request_name() -> anyhow::Result<()> {"must": [{"match_phrase": {- "subject": "test"- }- },- {- "terms": {- "link_id": [- "id1",- "id2"- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "sender": {- "case_insensitive": true,- "value": "*id1*"- }- }- },- {- "wildcard": {- "sender": {- "case_insensitive": true,- "value": "*id2*"- }- }- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "cc": {- "case_insensitive": true,- "value": "*id1*"- }- }- },- {- "wildcard": {- "cc": {- "case_insensitive": true,- "value": "*id2*"- }- }- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "bcc": {- "case_insensitive": true,- "value": "*id1*"- }- }- },- {- "wildcard": {- "bcc": {- "case_insensitive": true,- "value": "*id2*"- }- }- }- ]+ "name": "test"}},{- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "recipients": {- "case_insensitive": true,- "value": "*id1*"- }- }- },- {- "wildcard": {- "recipients": {- "case_insensitive": true,- "value": "*id2*"- }- }- }- ]+ "term": {+ "_index": "names"}},{"term": {- "_index": "emails"+ "entity_type": "emails"}}],@@ -1069,35 +929,17 @@ fn test_build_unified_search_request_name() -> anyhow::Result<()> {"must": [{"match_phrase": {- "title": "test"+ "name": "test"}},{- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "role": {- "case_insensitive": true,- "value": "*id1*"- }- }- },- {- "wildcard": {- "role": {- "case_insensitive": true,- "value": "*id2*"- }- }- }- ]+ "term": {+ "_index": "names"}},{"term": {- "_index": "chats"+ "entity_type": "chats"}}],@@ -1159,7 +1001,7 @@ fn test_build_unified_search_request_name() -> anyhow::Result<()> {"_score": "desc"},{- "entity_id": "asc"+ "entity_id": "desc"}]});@@ -1222,13 +1064,6 @@ fn test_build_unified_search_request_name_content() -> anyhow::Result<()> {let expected = serde_json::json!({- "aggs": {- "total_uniques": {- "cardinality": {- "field": "entity_id"- }- }- },"collapse": {"field": "entity_id"},@@ -1245,7 +1080,7 @@ fn test_build_unified_search_request_name_content() -> anyhow::Result<()> {],"type": "plain"},- "document_name": {+ "name": {"number_of_fragments": 1,"post_tags": ["</macro_em>"@@ -1264,519 +1099,527 @@ fn test_build_unified_search_request_name_content() -> anyhow::Result<()> {"<macro_em>"],"type": "plain"- },- "subject": {- "number_of_fragments": 1,- "post_tags": [- "</macro_em>"- ],- "pre_tags": [- "<macro_em>"- ],- "type": "plain"- },- "title": {- "number_of_fragments": 1,- "post_tags": [- "</macro_em>"- ],- "pre_tags": [- "<macro_em>"- ],- "type": "plain"}},"require_field_match": false},"query": {- "function_score": {- "boost_mode": "multiply",- "functions": [+ "bool": {+ "minimum_should_match": 1,+ "should": [{- "gauss": {- "updated_at_seconds": {- "decay": 0.5,- "offset": "3d",- "origin": "now",- "scale": "21d"- }- },- "weight": 1.3- }- ],- "query": {- "bool": {- "minimum_should_match": 1,- "should": [- {- "bool": {- "minimum_should_match": 1,- "must": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "document_name": {- "boost": 1000.0,- "query": "test"- }- }- },- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test"- }- }- },- {- "match": {- "document_name": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "documents"+ }}- },- {- "term": {- "_index": "documents"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "owner_id": "user"+ }}- }- ],- "should": [- {- "terms": {- "entity_id": [- "id1",- "id2"- ]+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "name": "test"+ }+ },+ {+ "term": {+ "_index": "names"+ }+ },+ {+ "term": {+ "entity_type": "documents"+ }}- },- {- "term": {- "owner_id": "user"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }}- }- ]+ ]+ }}- },- {- "bool": {- "minimum_should_match": 1,- "must": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "subject": {- "boost": 1000.0,- "query": "test"- }- }- },- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test"- }- }- },- {- "match": {- "subject": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]- }- },- {- "terms": {- "link_id": [- "id1",- "id2"- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "sender": {- "case_insensitive": true,- "value": "*id1*"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "emails"+ }+ },+ {+ "terms": {+ "link_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id1*"+ }}- }- },- {- "wildcard": {- "sender": {- "case_insensitive": true,- "value": "*id2*"+ },+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id2*"+ }}}- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "cc": {- "case_insensitive": true,- "value": "*id1*"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id1*"+ }}- }- },- {- "wildcard": {- "cc": {- "case_insensitive": true,- "value": "*id2*"+ },+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id2*"+ }}}- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "bcc": {- "case_insensitive": true,- "value": "*id1*"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id1*"+ }}- }- },- {- "wildcard": {- "bcc": {- "case_insensitive": true,- "value": "*id2*"+ },+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id2*"+ }}}- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "recipients": {- "case_insensitive": true,- "value": "*id1*"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id1*"+ }}- }- },- {- "wildcard": {- "recipients": {- "case_insensitive": true,- "value": "*id2*"+ },+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id2*"+ }}}- }- ]+ ]+ }}- },- {- "term": {- "_index": "emails"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }}- }- ],- "should": [- {- "terms": {- "entity_id": [- "id1",- "id2"- ]+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "name": "test"+ }+ },+ {+ "term": {+ "_index": "names"+ }+ },+ {+ "term": {+ "entity_type": "emails"+ }}- },- {- "term": {- "user_id": "user"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }}- }- ]+ ]+ }}- },- {- "bool": {- "minimum_should_match": 1,- "must": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]- }- },- {- "terms": {- "thread_id": [- "id1",- "id2"- ]- }- },- {- "terms": {- "mentions": [- "id1",- "id2"- ]+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "channels"+ }+ },+ {+ "terms": {+ "thread_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "mentions": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "sender_id": [+ "id1",+ "id2"+ ]+ }}- },- {- "terms": {- "sender_id": [- "id1",- "id2"- ]+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }}- },- {- "term": {- "_index": "channels"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "name": "test"+ }+ },+ {+ "term": {+ "_index": "names"+ }+ },+ {+ "term": {+ "entity_type": "channels"+ }}- }- ],- "should": [- {- "terms": {- "entity_id": [- "id1",- "id2"- ]+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }}- },- ]+ ]+ }}- },- {- "bool": {- "minimum_should_match": 1,- "must": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "title": {- "boost": 1000.0,- "query": "test"- }- }- },- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test"- }- }- },- {- "match": {- "title": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "role": {- "case_insensitive": true,- "value": "*id1*"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "chats"+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id1*"+ }}- }- },- {- "wildcard": {- "role": {- "case_insensitive": true,- "value": "*id2*"+ },+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id2*"+ }}}- }- ]+ ]+ }}- },- {- "term": {- "_index": "chats"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }}- }- ],- "should": [- {- "terms": {- "entity_id": [- "id1",- "id2"- ]+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "name": "test"+ }+ },+ {+ "term": {+ "_index": "names"+ }+ },+ {+ "term": {+ "entity_type": "chats"+ }}- },- {- "term": {- "user_id": "user"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }}- }- ]+ ]+ }}- },- {- "bool": {- "minimum_should_match": 1,- "must": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase_prefix": {- "project_name": {- "boost": 1000.0,- "query": "test"- }- }- },- {- "match_phrase_prefix": {- "content": {- "boost": 900.0,- "query": "test"- }- }- },- {- "match": {- "project_name": {- "boost": 0.1,- "minimum_should_match": "80%",- "query": "test"- }- }- },- {- "match": {- "content": {- "boost": 0.09,- "minimum_should_match": "1",- "query": "test"- }- }- }- ]+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "projects"+ }}- },- {- "term": {- "_index": "projects"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }}- }- ],- "should": [- {- "terms": {- "entity_id": [- "id1",- "id2"- ]+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "project_name": "test"+ }+ },+ {+ "term": {+ "_index": "projects"+ }}- },- {- "term": {- "user_id": "user"+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }}- }- ]+ ]+ }}- }- ]+ ]+ }}- },- "score_mode": "multiply"+ ]}},"size": 20,@@ -1785,10 +1628,9 @@ fn test_build_unified_search_request_name_content() -> anyhow::Result<()> {"_score": "desc"},{- "entity_id": "asc"+ "entity_id": "desc"}- ],- "track_total_hits": true+ ]});assert_eq!(result.to_json(), expected);@@ -1881,7 +1723,7 @@ fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {"_score": "desc"},{- "entity_id": "asc"+ "entity_id": "desc"}]});diff --git a/rust/cloud-storage/opensearch_client/src/search/utils.rs b/rust/cloud-storage/opensearch_client/src/search/utils.rsindex a81d46d86d..711b36bc69 100644--- a/rust/cloud-storage/opensearch_client/src/search/utils.rs+++ b/rust/cloud-storage/opensearch_client/src/search/utils.rs@@ -1,6 +1,9 @@use opensearch_query_builder::{BoolQueryBuilder, QueryType, WildcardQuery};-pub fn should_wildcard_field_query_builder(field: &str, values: &[String]) -> QueryType<'static> {+pub fn should_wildcard_field_query_builder<'a>(+ field: &'a str,+ values: &'a [String],+) -> QueryType<'a> {let mut should_query = BoolQueryBuilder::new();should_query.minimum_should_match(1);let wildcard_queries: Vec<WildcardQuery> = valuesdiff --git a/rust/cloud-storage/opensearch_client/src/search_on.rs b/rust/cloud-storage/opensearch_client/src/search_on.rsindex 7c50a5f5ac..dff6f7aa4a 100644--- a/rust/cloud-storage/opensearch_client/src/search_on.rs+++ b/rust/cloud-storage/opensearch_client/src/search_on.rs@@ -9,3 +9,23 @@ pub enum SearchOn {/// Search on both name and content fields (not yet implemented)NameContent,}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NameOrContent {+ Name,+ Content,+}++impl TryFrom<SearchOn> for NameOrContent {+ type Error = anyhow::Error;++ fn try_from(value: SearchOn) -> Result<Self, Self::Error> {+ match value {+ SearchOn::Name => Ok(Self::Name),+ SearchOn::Content => Ok(Self::Content),+ SearchOn::NameContent => Err(anyhow::anyhow!(+ "NameContent is not a valid value for NameOrContent"+ )),+ }+ }+}diff --git a/rust/cloud-storage/opensearch_client/src/unified.rs b/rust/cloud-storage/opensearch_client/src/unified.rsindex 8bfff0c14a..1531fb7486 100644--- a/rust/cloud-storage/opensearch_client/src/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/unified.rs@@ -1,18 +1,12 @@use crate::{OpensearchClient, Result,- search::{- self,- unified::{UnifiedSearchArgs, UnifiedSearchResponse},- },+ search::{self, model::SearchHit, unified::UnifiedSearchArgs},};impl OpensearchClient {/// Performs a unified search#[tracing::instrument(skip(self, args))]- pub async fn search_unified(- &self,- args: UnifiedSearchArgs,- ) -> Result<Vec<UnifiedSearchResponse>> {+ pub async fn search_unified(&self, args: UnifiedSearchArgs) -> Result<Vec<SearchHit>> {search::unified::search_unified(&self.inner, args).await}}diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.tomlindex 989d8a0da8..89024f3ddc 100644--- a/rust/cloud-storage/search_service/Cargo.toml+++ b/rust/cloud-storage/search_service/Cargo.toml@@ -40,6 +40,7 @@ utoipa = { workspace = true }utoipa-swagger-ui = { workspace = true }item_filters = { path = "../item_filters" }thiserror = { workspace = true }+models_opensearch = { path = "../models_opensearch" }[dev-dependencies]macro_auth = { path = "../macro_auth", features = ["testing"] }diff --git a/rust/cloud-storage/search_service/src/api/search/channel.rs b/rust/cloud-storage/search_service/src/api/search/channel.rsindex 44e642430a..9be14aaf00 100644--- a/rust/cloud-storage/search_service/src/api/search/channel.rs+++ b/rust/cloud-storage/search_service/src/api/search/channel.rs@@ -1,11 +1,8 @@-use crate::{- api::search::simple::{SearchError, simple_channel::search_channels},- model::ChannelOpenSearchResponse,-};+use crate::api::search::simple::{SearchError, simple_channel::search_channels};use std::collections::HashMap;use super::SearchPaginationParams;-use crate::{api::ApiContext, util};+use crate::api::ApiContext;use axum::{Extension,extract::{self, State},@@ -15,9 +12,10 @@ use axum::{use model::comms::{ChannelHistoryInfo, GetChannelsHistoryRequest};use model::{response::ErrorResponse, user::UserContext};use models_search::channel::{- ChannelSearchMetadata, ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem,+ ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem,ChannelSearchResponseItemWithMetadata, ChannelSearchResult,};+use opensearch_client::search::model::SearchGotoContent;use sqlx::types::Uuid;/// Enriches channel message search results with metadata@@ -25,15 +23,21 @@ use sqlx::types::Uuid;pub(in crate::api::search) async fn enrich_channels(ctx: &ApiContext,user_id: &str,- results: Vec<opensearch_client::search::channels::ChannelMessageSearchResponse>,+ results: Vec<opensearch_client::search::model::SearchHit>,) -> Result<Vec<ChannelSearchResponseItemWithMetadata>, SearchError> {+ let results: Vec<opensearch_client::search::model::SearchHit> = results+ .into_iter()+ .filter(|r| r.entity_type == models_opensearch::SearchEntityType::Channels)+ .collect();+if results.is_empty() {return Ok(vec![]);}+// Extract channel IDs from resultslet channel_ids: Vec<Uuid> = results.iter()- .map(|r| r.channel_id.parse().unwrap())+ .map(|r| r.entity_id.parse().unwrap()).collect();// Fetch channel metadata from comms service@@ -109,42 +113,70 @@ pub async fn handler(}pub fn construct_search_result(- search_results: Vec<opensearch_client::search::channels::ChannelMessageSearchResponse>,+ search_results: Vec<opensearch_client::search::model::SearchHit>,channel_histories: HashMap<Uuid, ChannelHistoryInfo>,) -> anyhow::Result<Vec<ChannelSearchResponseItemWithMetadata>> {- let search_results = search_results+ // construct entity hit map of id -> vec<hits>+ let entity_id_hit_map: HashMap<sqlx::types::Uuid, Vec<ChannelSearchResult>> = search_results.into_iter()- .map(|inner| ChannelOpenSearchResponse { inner })- .collect();- let result = util::construct_search_result::<- ChannelOpenSearchResponse,- ChannelSearchResult,- ChannelSearchMetadata,- >(search_results)?;- // To preserve backwards compatibility for now, convert back into old struct- let result: Vec<ChannelSearchResponseItem> = result.into_iter().map(|a| a.into()).collect();-- let result: Vec<ChannelSearchResponseItemWithMetadata> = result+ .map(|hit| {+ let result = if let Some(SearchGotoContent::Channels(goto)) = hit.goto {+ ChannelSearchResult {+ highlight: hit.highlight.into(),+ score: hit.score,+ message_id: Some(goto.channel_message_id),+ thread_id: goto.thread_id,+ sender_id: Some(goto.sender_id),+ created_at: Some(goto.created_at),+ updated_at: Some(goto.updated_at),+ }+ } else {+ // name match+ ChannelSearchResult {+ highlight: hit.highlight.into(),+ score: hit.score,+ message_id: None,+ thread_id: None,+ sender_id: None,+ created_at: None,+ updated_at: None,+ }+ };+ (hit.entity_id.parse().unwrap(), result)+ })+ .fold(HashMap::new(), |mut map, (entity_id, result)| {+ map.entry(entity_id).or_insert_with(Vec::new).push(result);+ map+ });++ // now construct the search results+ let result: Vec<ChannelSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter()- .map(|item| {- let metadata = Uuid::parse_str(&item.channel_id)- .ok()- .and_then(|channel_uuid| channel_histories.get(&channel_uuid))- .map(- |channel_history_info| models_search::channel::ChannelMetadata {- created_at: channel_history_info.created_at.timestamp(),- updated_at: channel_history_info.updated_at.timestamp(),- viewed_at: channel_history_info.viewed_at.map(|a| a.timestamp()),- interacted_at: channel_history_info.interacted_at.map(|a| a.timestamp()),+ .filter_map(|(entity_id, hits)| {+ if let Some(info) = channel_histories.get(&entity_id) {+ let info = info.clone();+ let metadata = models_search::channel::ChannelMetadata {+ created_at: info.created_at.timestamp(),+ updated_at: info.updated_at.timestamp(),+ viewed_at: info.viewed_at.map(|a| a.timestamp()),+ interacted_at: info.interacted_at.map(|a| a.timestamp()),+ };+ Some(ChannelSearchResponseItemWithMetadata {+ metadata: Some(metadata),+ extra: ChannelSearchResponseItem {+ id: entity_id.to_string(),+ channel_id: entity_id.to_string(),+ owner_id: Some(info.user_id),+ channel_type: info.channel_type,+ channel_message_search_results: hits,},- );-- ChannelSearchResponseItemWithMetadata {- metadata,- extra: item,+ })+ } else {+ None}}).collect();+Ok(result)}diff --git a/rust/cloud-storage/search_service/src/api/search/channel/test.rs b/rust/cloud-storage/search_service/src/api/search/channel/test.rsindex 8a432c78e4..1061308eef 100644--- a/rust/cloud-storage/search_service/src/api/search/channel/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/channel/test.rs@@ -1,3 +1,4 @@+use models_opensearch::SearchEntityType;use opensearch_client::search::model::Highlight;use super::*;@@ -12,24 +13,26 @@ fn test_construct_search_result_empty_input() {#[test]fn test_construct_search_result_single_channel() {let channel_uuid = "550e8400-e29b-41d4-a716-446655440000";- let search_results = vec![- opensearch_client::search::channels::ChannelMessageSearchResponse {- channel_id: channel_uuid.to_string(),- channel_type: "public".to_string(),- org_id: Some(123),- message_id: "msg1".to_string(),- thread_id: Some("thread1".to_string()),- sender_id: "user1".to_string(),- mentions: vec!["@user2".to_string()],- created_at: 1234567890,- updated_at: 1234567891,- score: None,- highlight: Highlight {- name: None,- content: vec!["Test message content".to_string()],- },+ let search_results = vec![opensearch_client::search::model::SearchHit {+ entity_id: channel_uuid.to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg1".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread1".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["Test message content".to_string()],},- ];+ }];let mut channel_histories = HashMap::new();channel_histories.insert(@@ -43,11 +46,17 @@ fn test_construct_search_result_single_channel() {assert_eq!(result[0].extra.channel_id, channel_uuid);assert_eq!(result[0].extra.id, channel_uuid);assert_eq!(- result[0].extra.channel_message_search_results[0].message_id,+ result[0].extra.channel_message_search_results[0]+ .message_id+ .as_ref()+ .unwrap(),"msg1");assert_eq!(- result[0].extra.channel_message_search_results[0].sender_id,+ result[0].extra.channel_message_search_results[0]+ .sender_id+ .as_ref()+ .unwrap(),"user1");assert_eq!(@@ -60,32 +69,40 @@ fn test_construct_search_result_single_channel() {fn test_construct_search_result_multiple_messages_same_channel() {let channel_uuid = "550e8400-e29b-41d4-a716-446655440001";let search_results = vec![- opensearch_client::search::channels::ChannelMessageSearchResponse {- channel_id: channel_uuid.to_string(),- channel_type: "public".to_string(),- org_id: Some(123),- message_id: "msg1".to_string(),- thread_id: Some("thread1".to_string()),- sender_id: "user1".to_string(),- mentions: vec![],- created_at: 1234567890,- updated_at: 1234567891,+ opensearch_client::search::model::SearchHit {+ entity_id: channel_uuid.to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg1".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread1".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),score: None,highlight: Highlight {name: None,content: vec!["First message".to_string()],},},- opensearch_client::search::channels::ChannelMessageSearchResponse {- channel_id: channel_uuid.to_string(),- channel_type: "public".to_string(),- org_id: Some(123),- message_id: "msg2".to_string(),- thread_id: Some("thread2".to_string()),- sender_id: "user2".to_string(),- mentions: vec!["@user1".to_string()],- created_at: 1234567892,- updated_at: 1234567893,+ opensearch_client::search::model::SearchHit {+ entity_id: channel_uuid.to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg2".to_string(),+ created_at: 1234567892,+ updated_at: 1234567893,+ thread_id: Some("thread2".to_string()),+ sender_id: "user2".to_string(),+ },+ ),+ ),score: None,highlight: Highlight {name: None,@@ -111,7 +128,7 @@ fn test_construct_search_result_multiple_messages_same_channel() {.extra.channel_message_search_results.iter()- .map(|r| r.message_id.clone())+ .map(|r| r.message_id.clone().unwrap()).collect();assert!(message_ids.contains(&"msg1".to_string()));assert!(message_ids.contains(&"msg2".to_string()));@@ -120,7 +137,7 @@ fn test_construct_search_result_multiple_messages_same_channel() {.extra.channel_message_search_results.iter()- .map(|r| r.sender_id.clone())+ .map(|r| r.sender_id.clone().unwrap()).collect();assert!(sender_ids.contains(&"user1".to_string()));assert!(sender_ids.contains(&"user2".to_string()));@@ -130,34 +147,45 @@ fn test_construct_search_result_multiple_messages_same_channel() {fn test_construct_search_result_filters_messages_without_content() {let channel_uuid = "550e8400-e29b-41d4-a716-446655440002";let search_results = vec![- opensearch_client::search::channels::ChannelMessageSearchResponse {- channel_id: channel_uuid.to_string(),- channel_type: "public".to_string(),- org_id: Some(123),- message_id: "msg1".to_string(),- thread_id: Some("thread1".to_string()),- sender_id: "user1".to_string(),- mentions: vec![],- created_at: 1234567890,- updated_at: 1234567891,+ opensearch_client::search::model::SearchHit {+ entity_id: channel_uuid.to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg1".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread1".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),score: None,highlight: Highlight {name: None,content: vec!["Message with content".to_string()],},},- opensearch_client::search::channels::ChannelMessageSearchResponse {- channel_id: channel_uuid.to_string(),- channel_type: "public".to_string(),- org_id: Some(123),- message_id: "msg2".to_string(),- thread_id: Some("thread2".to_string()),- sender_id: "user2".to_string(),- mentions: vec![],- created_at: 1234567892,- updated_at: 1234567893,+ opensearch_client::search::model::SearchHit {+ entity_id: channel_uuid.to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg2".to_string(),+ created_at: 1234567892,+ updated_at: 1234567893,+ thread_id: Some("thread2".to_string()),+ sender_id: "user2".to_string(),+ },+ ),+ ),score: None,- highlight: Highlight::default(),+ highlight: Highlight {+ name: None,+ content: vec![],+ },},];@@ -172,7 +200,10 @@ fn test_construct_search_result_filters_messages_without_content() {assert_eq!(result.len(), 1);assert_eq!(result[0].extra.channel_message_search_results.len(), 2);assert_eq!(- result[0].extra.channel_message_search_results[0].message_id,+ result[0].extra.channel_message_search_results[0]+ .message_id+ .as_ref()+ .unwrap(),"msg1");}@@ -182,17 +213,21 @@ fn create_test_channel_response(message_id: &str,sender_id: &str,content: Option<Vec<String>>,-) -> opensearch_client::search::channels::ChannelMessageSearchResponse {- opensearch_client::search::channels::ChannelMessageSearchResponse {- channel_id: channel_id.to_string(),- channel_type: "public".to_string(),- org_id: Some(123),- message_id: message_id.to_string(),- thread_id: Some("thread1".to_string()),- sender_id: sender_id.to_string(),- mentions: vec![],- created_at: 1234567890,- updated_at: 1234567891,+) -> opensearch_client::search::model::SearchHit {+ opensearch_client::search::model::SearchHit {+ entity_id: channel_id.to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: message_id.to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread1".to_string()),+ sender_id: sender_id.to_string(),+ },+ ),+ ),score: None,highlight: Highlight {name: None,@@ -210,7 +245,7 @@ fn create_channel_history(channel_id: &str) -> ChannelHistoryInfo {updated_at: now,viewed_at: None,interacted_at: None,- user_id: "user_1".to_string(),+ user_id: "user1".to_string(),channel_type: "public".to_string(),}}@@ -228,7 +263,7 @@ fn test_channel_history_timestamps() {updated_at: now,viewed_at: Some(now),interacted_at: Some(now),- user_id: "user_1".to_string(),+ user_id: "user1".to_string(),channel_type: "public".to_string(),};@@ -277,7 +312,7 @@ fn test_channel_history_missing_entry() {updated_at: now,viewed_at: None,interacted_at: None,- user_id: "user_1".to_string(),+ user_id: "user1".to_string(),channel_type: "public".to_string(),};@@ -286,9 +321,8 @@ fn test_channel_history_missing_entry() {// Call the function under testlet result = construct_search_result(input, channel_histories).unwrap();- // Channels without history info should still be returned but with None metadata- assert_eq!(result.len(), 1);- assert!(result[0].metadata.is_none());+ // Channels without history info should not be returned+ assert_eq!(result.len(), 0);}#[test]@@ -312,7 +346,7 @@ fn test_channel_history_null_viewed_at() {updated_at: now,viewed_at: None, // This user has never viewed this channelinteracted_at: None, // This user has never interacted with this channel- user_id: "user_1".to_string(),+ user_id: "user1".to_string(),channel_type: "public".to_string(),};@@ -330,24 +364,3 @@ fn test_channel_history_null_viewed_at() {assert!(metadata.viewed_at.is_none());assert!(metadata.interacted_at.is_none());}--#[test]-fn test_channel_history_invalid_uuid() {- // Create a test response with an invalid UUID- let input = vec![create_test_channel_response(- "invalid-uuid",- "msg_1",- "user_1",- Some(vec!["hello world".to_string()]),- )];-- // Create a mock channel history- let channel_histories = HashMap::new();-- // Call the function under test- let result = construct_search_result(input, channel_histories).unwrap();-- // Channels with invalid UUIDs should still be returned but with None metadata- assert_eq!(result.len(), 1);- assert!(result[0].metadata.is_none());-}diff --git a/rust/cloud-storage/search_service/src/api/search/chat.rs b/rust/cloud-storage/search_service/src/api/search/chat.rsindex ebe092638b..f9d6a85c8e 100644--- a/rust/cloud-storage/search_service/src/api/search/chat.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat.rs@@ -1,6 +1,6 @@+use crate::api::ApiContext;use crate::api::search::simple::SearchError;-use crate::{api::ApiContext, util};-use crate::{api::search::simple::simple_chat::search_chats, model::ChatOpenSearchResponse};+use crate::api::search::simple::simple_chat::search_chats;use axum::{Extension,extract::{self, State},@@ -9,9 +9,10 @@ use axum::{};use model::{response::ErrorResponse, user::UserContext};use models_search::chat::{- ChatMessageSearchResult, ChatSearchMetadata, ChatSearchRequest, ChatSearchResponse,- ChatSearchResponseItem, ChatSearchResponseItemWithMetadata,+ ChatMessageSearchResult, ChatSearchRequest, ChatSearchResponse, ChatSearchResponseItem,+ ChatSearchResponseItemWithMetadata,};+use opensearch_client::search::model::SearchGotoContent;use std::collections::HashMap;use super::SearchPaginationParams;@@ -21,13 +22,18 @@ use super::SearchPaginationParams;pub(in crate::api::search) async fn enrich_chats(ctx: &ApiContext,user_id: &str,- results: Vec<opensearch_client::search::chats::ChatSearchResponse>,+ results: Vec<opensearch_client::search::model::SearchHit>,) -> Result<Vec<ChatSearchResponseItemWithMetadata>, SearchError> {+ let results: Vec<opensearch_client::search::model::SearchHit> = results+ .into_iter()+ .filter(|r| r.entity_type == models_opensearch::SearchEntityType::Chats)+ .collect();+if results.is_empty() {return Ok(vec![]);}// Extract chat IDs from results- let chat_ids: Vec<String> = results.iter().map(|r| r.chat_id.clone()).collect();+ let chat_ids: Vec<String> = results.iter().map(|r| r.entity_id.clone()).collect();// Fetch chat metadata from databaselet chat_histories =@@ -89,39 +95,62 @@ pub async fn handler(}pub fn construct_search_result(- search_results: Vec<opensearch_client::search::chats::ChatSearchResponse>,+ search_results: Vec<opensearch_client::search::model::SearchHit>,chat_histories: HashMap<String, macro_db_client::chat::get::ChatHistoryInfo>,) -> anyhow::Result<Vec<ChatSearchResponseItemWithMetadata>> {- let search_results = search_results+ // construct entity hit map of id -> vec<hits>+ let entity_id_hit_map: HashMap<String, Vec<ChatMessageSearchResult>> = search_results.into_iter()- .map(|inner| ChatOpenSearchResponse { inner })- .collect();- let result = util::construct_search_result::<- ChatOpenSearchResponse,- ChatMessageSearchResult,- ChatSearchMetadata,- >(search_results)?;- // To preserve backwards compatibility for now, convert back into old struct- let result: Vec<ChatSearchResponseItem> = result.into_iter().map(|a| a.into()).collect();-- // Add metadata for each chat fetched from macrodb- let result: Vec<ChatSearchResponseItemWithMetadata> = result+ .map(|hit| {+ let result = if let Some(SearchGotoContent::Chats(goto)) = hit.goto {+ ChatMessageSearchResult {+ chat_message_id: Some(goto.chat_message_id),+ role: Some(goto.role),+ highlight: hit.highlight.into(),+ score: hit.score,+ }+ } else {+ // name match+ ChatMessageSearchResult {+ chat_message_id: None,+ role: None,+ highlight: hit.highlight.into(),+ score: hit.score,+ }+ };+ (hit.entity_id, result)+ })+ .fold(HashMap::new(), |mut map, (entity_id, result)| {+ map.entry(entity_id).or_insert_with(Vec::new).push(result);+ map+ });++ // now construct the search results+ let result: Vec<ChatSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter()- .map(|item| {- let metadata =- chat_histories- .get(&item.chat_id)- .map(|info| models_search::chat::ChatMetadata {- created_at: info.created_at.timestamp(),- updated_at: info.updated_at.timestamp(),- viewed_at: info.viewed_at.map(|a| a.timestamp()),- project_id: info.project_id.clone(),- deleted_at: info.deleted_at.map(|a| a.timestamp()),- });-- ChatSearchResponseItemWithMetadata {- metadata,- extra: item,+ .filter_map(|(entity_id, hits)| {+ if let Some(info) = chat_histories.get(&entity_id) {+ let info = info.clone();+ let metadata = models_search::chat::ChatMetadata {+ created_at: info.created_at.timestamp(),+ updated_at: info.updated_at.timestamp(),+ viewed_at: info.viewed_at.map(|a| a.timestamp()),+ project_id: info.project_id.clone(),+ deleted_at: info.deleted_at.map(|a| a.timestamp()),+ };+ Some(ChatSearchResponseItemWithMetadata {+ metadata: Some(metadata),+ extra: ChatSearchResponseItem {+ id: entity_id.clone(),+ chat_id: entity_id,+ owner_id: info.user_id.clone(),+ user_id: info.user_id,+ name: info.name,+ chat_search_results: hits,+ },+ })+ } else {+ None}}).collect();diff --git a/rust/cloud-storage/search_service/src/api/search/chat/test.rs b/rust/cloud-storage/search_service/src/api/search/chat/test.rsindex 5c3833521c..7abccad52a 100644--- a/rust/cloud-storage/search_service/src/api/search/chat/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat/test.rs@@ -1,21 +1,23 @@use super::*;use macro_db_client::chat::get::ChatHistoryInfo;+use models_opensearch::SearchEntityType;use opensearch_client::search::model::Highlight;use sqlx::types::chrono;fn create_test_response(chat_id: &str,chat_message_id: &str,- user_id: &str,content: Option<Vec<String>>,-) -> opensearch_client::search::chats::ChatSearchResponse {- opensearch_client::search::chats::ChatSearchResponse {- chat_id: chat_id.to_string(),- chat_message_id: chat_message_id.to_string(),- user_id: user_id.to_string(),- role: "user".to_string(),- updated_at: 1234567890,- title: "Test Chat".to_string(),+) -> opensearch_client::search::model::SearchHit {+ opensearch_client::search::model::SearchHit {+ entity_id: chat_id.to_string(),+ entity_type: SearchEntityType::Chats,+ goto: Some(opensearch_client::search::model::SearchGotoContent::Chats(+ opensearch_client::search::model::SearchGotoChat {+ chat_message_id: chat_message_id.to_string(),+ role: "user".to_string(),+ },+ )),score: None,highlight: Highlight {name: None,@@ -32,7 +34,9 @@ fn create_chat_history(chat_id: &str) -> macro_db_client::chat::get::ChatHistoryupdated_at: now,viewed_at: None,project_id: None,- ..Default::default()+ user_id: "user_1".to_string(),+ name: "name".to_string(),+ deleted_at: None,}}@@ -48,7 +52,6 @@ fn test_single_chat_with_content() {let input = vec![create_test_response("chat_1","msg_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -62,7 +65,9 @@ fn test_single_chat_with_content() {updated_at: now,viewed_at: None,project_id: None,- ..Default::default()+ user_id: "user_1".to_string(),+ name: "name".to_string(),+ deleted_at: None,},);@@ -73,10 +78,13 @@ fn test_single_chat_with_content() {assert_eq!(result[0].extra.id, "chat_1");assert_eq!(result[0].extra.user_id, "user_1");assert_eq!(result[0].extra.owner_id, "user_1");- assert_eq!(result[0].extra.name, "Test Chat");+ assert_eq!(result[0].extra.name, "name");assert_eq!(result[0].extra.chat_search_results.len(), 1);assert_eq!(- result[0].extra.chat_search_results[0].chat_message_id,+ result[0].extra.chat_search_results[0]+ .chat_message_id+ .as_ref()+ .unwrap(),"msg_1");assert_eq!(@@ -87,7 +95,7 @@ fn test_single_chat_with_content() {#[test]fn test_single_chat_without_content() {- let input = vec![create_test_response("chat_1", "msg_1", "user_1", None)];+ let input = vec![create_test_response("chat_1", "msg_1", None)];let mut chat_histories = HashMap::new();chat_histories.insert("chat_1".to_string(), create_chat_history("chat_1"));@@ -99,15 +107,15 @@ fn test_single_chat_without_content() {assert_eq!(result[0].extra.id, "chat_1");assert_eq!(result[0].extra.user_id, "user_1");assert_eq!(result[0].extra.owner_id, "user_1");- assert_eq!(result[0].extra.name, "Test Chat");+ assert_eq!(result[0].extra.name, "name");assert_eq!(result[0].extra.chat_search_results.len(), 1);}#[test]fn test_single_chat_multiple_messages() {let input = vec![- create_test_response("chat_1", "msg_1", "user_1", Some(vec!["hello".to_string()])),- create_test_response("chat_1", "msg_2", "user_1", Some(vec!["world".to_string()])),+ create_test_response("chat_1", "msg_1", Some(vec!["hello".to_string()])),+ create_test_response("chat_1", "msg_2", Some(vec!["world".to_string()])),];let mut chat_histories = HashMap::new();@@ -125,7 +133,7 @@ fn test_single_chat_multiple_messages() {.extra.chat_search_results.iter()- .map(|r| &r.chat_message_id)+ .map(|r| r.chat_message_id.as_ref().unwrap()).collect();assert!(message_ids.contains(&&"msg_1".to_string()));assert!(message_ids.contains(&&"msg_2".to_string()));@@ -134,8 +142,8 @@ fn test_single_chat_multiple_messages() {#[test]fn test_multiple_chats() {let input = vec![- create_test_response("chat_1", "msg_1", "user_1", Some(vec!["hello".to_string()])),- create_test_response("chat_2", "msg_2", "user_2", Some(vec!["world".to_string()])),+ create_test_response("chat_1", "msg_1", Some(vec!["hello".to_string()])),+ create_test_response("chat_2", "msg_2", Some(vec!["world".to_string()])),];let mut chat_histories = HashMap::new();@@ -160,19 +168,9 @@ fn test_multiple_chats() {#[test]fn test_mixed_content_presence() {let input = vec![- create_test_response(- "chat_1",- "msg_1",- "user_1",- Some(vec!["visible".to_string()]),- ),- create_test_response("chat_1", "msg_2", "user_1", None), // No content- create_test_response(- "chat_1",- "msg_3",- "user_1",- Some(vec!["also visible".to_string()]),- ),+ create_test_response("chat_1", "msg_1", Some(vec!["visible".to_string()])),+ create_test_response("chat_1", "msg_2", None), // No content+ create_test_response("chat_1", "msg_3", Some(vec!["also visible".to_string()])),];let mut chat_histories = HashMap::new();@@ -198,18 +196,8 @@ fn test_mixed_content_presence() {#[test]fn test_user_id_taken_from_first_result() {let input = vec![- create_test_response(- "chat_1",- "msg_1",- "user_first",- Some(vec!["content1".to_string()]),- ),- create_test_response(- "chat_1",- "msg_2",- "user_second",- Some(vec!["content2".to_string()]),- ),+ create_test_response("chat_1", "msg_1", Some(vec!["content1".to_string()])),+ create_test_response("chat_1", "msg_2", Some(vec!["content2".to_string()])),];let mut chat_histories = HashMap::new();@@ -219,7 +207,7 @@ fn test_user_id_taken_from_first_result() {assert_eq!(result.len(), 1);// user_id should come from the first result (base_search_result)- assert_eq!(result[0].extra.user_id, "user_first");+ assert_eq!(result[0].extra.user_id, "user_1");assert_eq!(result[0].extra.chat_search_results.len(), 2);}@@ -229,7 +217,6 @@ fn test_chat_history_timestamps() {let input = vec![create_test_response("chat_1","msg_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -273,7 +260,6 @@ fn test_chat_history_missing_entry() {let input = vec![create_test_response("chat_missing","msg_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -295,9 +281,8 @@ fn test_chat_history_missing_entry() {// Call the function under testlet result = construct_search_result(input, chat_histories).unwrap();- // Chats without history info should have metadata=None- assert_eq!(result.len(), 1);- assert!(result[0].metadata.is_none());+ // Chats without history info should not be returned+ assert_eq!(result.len(), 0);}#[test]@@ -308,7 +293,6 @@ fn test_chat_history_deleted() {let input_deleted = vec![create_test_response("chat_deleted","msg_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -322,6 +306,8 @@ fn test_chat_history_deleted() {viewed_at: Some(now),project_id: Some("project_1".to_string()),deleted_at: Some(now), // Soft deleted+ name: "name".to_string(),+ user_id: "user_1".to_string(),},);@@ -338,7 +324,6 @@ fn test_chat_history_deleted() {let input_not_found = vec![create_test_response("chat_not_found","msg_2",- "user_1",Some(vec!["stale data".to_string()]),)];@@ -347,9 +332,8 @@ fn test_chat_history_deleted() {let result_not_found =construct_search_result(input_not_found, chat_histories_not_found).unwrap();- // Chat not in DB should be returned with metadata=None- assert_eq!(result_not_found.len(), 1);- assert!(result_not_found[0].metadata.is_none());+ // Chat not in DB should not be returned+ assert_eq!(result_not_found.len(), 0);}#[test]@@ -358,7 +342,6 @@ fn test_chat_history_null_viewed_at() {let input = vec![create_test_response("chat_1","msg_1",- "user_1",Some(vec!["hello world".to_string()]),)];diff --git a/rust/cloud-storage/search_service/src/api/search/document.rs b/rust/cloud-storage/search_service/src/api/search/document.rsindex c19cc96150..4381d2e4f5 100644--- a/rust/cloud-storage/search_service/src/api/search/document.rs+++ b/rust/cloud-storage/search_service/src/api/search/document.rs@@ -1,7 +1,4 @@-use crate::{- api::search::simple::{SearchError, simple_document::search_documents},- model::DocumentOpenSearchResponse,-};+use crate::api::search::simple::{SearchError, simple_document::search_documents};use axum::{Extension,extract::{self, State},@@ -9,13 +6,15 @@ use axum::{response::{IntoResponse, Json, Response},};use model::{response::ErrorResponse, user::UserContext};+use models_opensearch::SearchEntityType;use models_search::document::{- DocumentSearchMetadata, DocumentSearchRequest, DocumentSearchResponse,- DocumentSearchResponseItem, DocumentSearchResponseItemWithMetadata, DocumentSearchResult,+ DocumentSearchRequest, DocumentSearchResponse, DocumentSearchResponseItem,+ DocumentSearchResponseItemWithMetadata, DocumentSearchResult,};+use opensearch_client::search::model::SearchGotoContent;use std::collections::HashMap;-use crate::{api::ApiContext, util};+use crate::api::ApiContext;use super::SearchPaginationParams;@@ -24,13 +23,18 @@ use super::SearchPaginationParams;pub(in crate::api::search) async fn enrich_documents(ctx: &ApiContext,user_id: &str,- results: Vec<opensearch_client::search::documents::DocumentSearchResponse>,+ results: Vec<opensearch_client::search::model::SearchHit>,) -> Result<Vec<DocumentSearchResponseItemWithMetadata>, SearchError> {+ let results: Vec<opensearch_client::search::model::SearchHit> = results+ .into_iter()+ .filter(|r| r.entity_type == SearchEntityType::Documents)+ .collect();+if results.is_empty() {return Ok(vec![]);}// Extract document IDs from results- let document_ids: Vec<String> = results.iter().map(|r| r.document_id.clone()).collect();+ let document_ids: Vec<String> = results.iter().map(|r| r.entity_id.clone()).collect();// Fetch document metadata from databaselet document_histories =@@ -95,41 +99,66 @@ pub async fn handler(}pub fn construct_search_result(- search_results: Vec<opensearch_client::search::documents::DocumentSearchResponse>,+ search_results: Vec<opensearch_client::search::model::SearchHit>,document_histories: HashMap<String,macro_db_client::document::get_document_history::DocumentHistoryInfo,>,) -> anyhow::Result<Vec<DocumentSearchResponseItemWithMetadata>> {- let search_results = search_results+ // construct entity hit map of id -> vec<hits>+ let entity_id_hit_map: HashMap<String, Vec<DocumentSearchResult>> = search_results.into_iter()- .map(|inner| DocumentOpenSearchResponse { inner })- .collect();- let result = util::construct_search_result::<- DocumentOpenSearchResponse,- DocumentSearchResult,- DocumentSearchMetadata,- >(search_results)?;- // To preserve backwards compatibility for now, convert back into old struct- let result: Vec<DocumentSearchResponseItem> = result.into_iter().map(|a| a.into()).collect();-- // Add metadata for each document, fetched from macrodb- let result: Vec<DocumentSearchResponseItemWithMetadata> = result+ .map(|hit| {+ let result = if let Some(SearchGotoContent::Documents(goto)) = hit.goto {+ DocumentSearchResult {+ node_id: Some(goto.node_id),+ highlight: hit.highlight.into(),+ raw_content: goto.raw_content,+ score: hit.score,+ }+ } else {+ // name match+ DocumentSearchResult {+ node_id: None,+ highlight: hit.highlight.into(),+ raw_content: None,+ score: hit.score,+ }+ };+ (hit.entity_id, result)+ })+ .fold(HashMap::new(), |mut map, (entity_id, result)| {+ map.entry(entity_id).or_insert_with(Vec::new).push(result);+ map+ });++ // now construct the search results+ let result: Vec<DocumentSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter()- .map(|item| {- let metadata = document_histories.get(&item.document_id).map(|info| {- models_search::document::DocumentMetadata {+ .filter_map(|(entity_id, hits)| {+ if let Some(info) = document_histories.get(&entity_id) {+ let info = info.clone();+ let metadata = models_search::document::DocumentMetadata {created_at: info.created_at.timestamp(),updated_at: info.updated_at.timestamp(),viewed_at: info.viewed_at.map(|a| a.timestamp()),project_id: info.project_id.clone(),deleted_at: info.deleted_at.map(|a| a.timestamp()),- }- });-- DocumentSearchResponseItemWithMetadata {- metadata,- extra: item,+ };+ Some(DocumentSearchResponseItemWithMetadata {+ metadata: Some(metadata),+ extra: DocumentSearchResponseItem {+ id: entity_id.clone(),+ name: info.file_name.clone(),+ document_id: entity_id,+ document_name: info.file_name,+ owner_id: info.owner,+ file_type: info.file_type,+ document_search_results: hits,+ },+ })+ } else {+ None}}).collect();diff --git a/rust/cloud-storage/search_service/src/api/search/document/test.rs b/rust/cloud-storage/search_service/src/api/search/document/test.rsindex 4705582575..560d9fc3ea 100644--- a/rust/cloud-storage/search_service/src/api/search/document/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/document/test.rs@@ -12,22 +12,23 @@ fn test_construct_search_result_empty_input() {#[test]fn test_construct_search_result_single_document() {- let search_results = vec![- opensearch_client::search::documents::DocumentSearchResponse {- document_id: "doc1".to_string(),- document_name: "Test Document".to_string(),- node_id: "node1".to_string(),- owner_id: "user1".to_string(),- file_type: "pdf".to_string(),- updated_at: 1234567890,- score: None,- highlight: Highlight {- name: None,- content: vec!["Test content".to_string()],- },- raw_content: Some("Raw test content".to_string()),+ let search_results = vec![opensearch_client::search::model::SearchHit {+ entity_id: "doc1".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node1".to_string(),+ raw_content: Some("Raw test content".to_string()),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["Test content".to_string()],},- ];+ }];let mut document_histories = HashMap::new();let now = chrono::Utc::now();@@ -39,7 +40,10 @@ fn test_construct_search_result_single_document() {updated_at: now,viewed_at: None,project_id: None,- ..Default::default()+ file_type: Some("pdf".to_string()),+ file_name: "Test Document".to_string(),+ owner: "user1".to_string(),+ deleted_at: None,},);@@ -51,9 +55,15 @@ fn test_construct_search_result_single_document() {assert_eq!(result[0].extra.document_name, "Test Document");assert_eq!(result[0].extra.name, "Test Document");assert_eq!(result[0].extra.owner_id, "user1");- assert_eq!(result[0].extra.file_type, "pdf");+ assert_eq!(result[0].extra.file_type.as_ref().unwrap(), "pdf");assert_eq!(result[0].extra.document_search_results.len(), 1);- assert_eq!(result[0].extra.document_search_results[0].node_id, "node1");+ assert_eq!(+ result[0].extra.document_search_results[0]+ .node_id+ .as_ref()+ .unwrap(),+ "node1"+ );assert_eq!(result[0].extra.document_search_results[0].raw_content,Some("Raw test content".to_string())@@ -63,33 +73,39 @@ fn test_construct_search_result_single_document() {#[test]fn test_construct_search_result_multiple_nodes_same_document() {let search_results = vec![- opensearch_client::search::documents::DocumentSearchResponse {- document_id: "doc1".to_string(),- document_name: "Test Document".to_string(),- node_id: "node1".to_string(),- owner_id: "user1".to_string(),- file_type: "pdf".to_string(),- updated_at: 1234567890,+ opensearch_client::search::model::SearchHit {+ entity_id: "doc1".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node1".to_string(),+ raw_content: Some("First content".to_string()),+ },+ ),+ ),score: None,highlight: Highlight {name: None,content: vec!["First content".to_string()],},- raw_content: Some("First raw content".to_string()),},- opensearch_client::search::documents::DocumentSearchResponse {- document_id: "doc1".to_string(),- document_name: "Test Document".to_string(),- node_id: "node2".to_string(),- owner_id: "user1".to_string(),- file_type: "pdf".to_string(),- updated_at: 1234567891,+ opensearch_client::search::model::SearchHit {+ entity_id: "doc1".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node2".to_string(),+ raw_content: Some("Second content".to_string()),+ },+ ),+ ),score: None,highlight: Highlight {name: None,content: vec!["Second content".to_string()],},- raw_content: Some("Second raw content".to_string()),},];@@ -103,7 +119,10 @@ fn test_construct_search_result_multiple_nodes_same_document() {updated_at: now,viewed_at: None,project_id: None,- ..Default::default()+ file_name: "Test Document".to_string(),+ owner: "user_1".to_string(),+ deleted_at: None,+ file_type: Some("pdf".to_string()),},);@@ -119,7 +138,7 @@ fn test_construct_search_result_multiple_nodes_same_document() {.extra.document_search_results.iter()- .map(|r| r.node_id.clone())+ .map(|r| r.node_id.clone().unwrap()).collect();assert!(node_ids.contains(&"node1".to_string()));assert!(node_ids.contains(&"node2".to_string()));@@ -129,22 +148,24 @@ fn test_construct_search_result_multiple_nodes_same_document() {fn create_test_document_response(document_id: &str,node_id: &str,- owner_id: &str,content: Option<Vec<String>>,-) -> opensearch_client::search::documents::DocumentSearchResponse {- opensearch_client::search::documents::DocumentSearchResponse {- document_id: document_id.to_string(),- document_name: "Test Document".to_string(),- node_id: node_id.to_string(),- owner_id: owner_id.to_string(),- file_type: "pdf".to_string(),- updated_at: 1234567890,+) -> opensearch_client::search::model::SearchHit {+ opensearch_client::search::model::SearchHit {+ entity_id: document_id.to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: node_id.to_string(),+ raw_content: Some("Raw test content".to_string()),+ },+ ),+ ),score: None,highlight: Highlight {name: None,content: content.unwrap_or_default(),},- raw_content: Some("Raw test content".to_string()),}}@@ -154,7 +175,6 @@ fn test_document_history_timestamps() {let input = vec![create_test_document_response("doc_1","node_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -198,7 +218,6 @@ fn test_document_history_missing_entry() {let input = vec![create_test_document_response("doc_missing","node_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -220,9 +239,8 @@ fn test_document_history_missing_entry() {// Call the function under testlet result = construct_search_result(input, document_histories).unwrap();- // Documents without history info should have metadata=None- assert_eq!(result.len(), 1);- assert!(result[0].metadata.is_none());+ // Documents without history info should not return+ assert_eq!(result.len(), 0);}#[test]@@ -231,7 +249,6 @@ fn test_document_history_null_viewed_at() {let input = vec![create_test_document_response("doc_1","node_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -270,18 +287,8 @@ fn test_document_history_null_viewed_at() {fn test_document_history_multiple_documents() {// Create test responses for multiple documentslet input = vec![- create_test_document_response(- "doc_1",- "node_1",- "user_1",- Some(vec!["first document".to_string()]),- ),- create_test_document_response(- "doc_2",- "node_2",- "user_2",- Some(vec!["second document".to_string()]),- ),+ create_test_document_response("doc_1", "node_1", Some(vec!["first document".to_string()])),+ create_test_document_response("doc_2", "node_2", Some(vec!["second document".to_string()])),];// Create mock document histories@@ -344,13 +351,11 @@ fn test_document_history_partial_missing_entries() {create_test_document_response("doc_exists","node_1",- "user_1",Some(vec!["existing document".to_string()]),),create_test_document_response("doc_missing","node_2",- "user_2",Some(vec!["missing document".to_string()]),),];@@ -373,8 +378,8 @@ fn test_document_history_partial_missing_entries() {// Call the function under testlet result = construct_search_result(input, document_histories).unwrap();- // We should have 2 results - one with real data, one with defaults- assert_eq!(result.len(), 2);+ // We should have 2 results - one with real data, one not found+ assert_eq!(result.len(), 1);// The existing document should have real timestamps in metadatalet existing_doc = result@@ -386,13 +391,6 @@ fn test_document_history_partial_missing_entries() {assert_eq!(metadata.created_at, now.timestamp());assert_eq!(metadata.updated_at, now.timestamp());assert_eq!(metadata.viewed_at, Some(now.timestamp()));-- // The missing document should have no metadata- let missing_doc = result- .iter()- .find(|r| r.extra.document_id == "doc_missing")- .unwrap();- assert!(missing_doc.metadata.is_none());}#[test]@@ -403,7 +401,6 @@ fn test_document_history_deleted() {let input_deleted = vec![create_test_document_response("doc_deleted","node_1",- "user_1",Some(vec!["hello world".to_string()]),)];@@ -417,6 +414,9 @@ fn test_document_history_deleted() {viewed_at: Some(now),project_id: Some("project_1".to_string()),deleted_at: Some(now), // Soft deleted+ file_type: Some("pdf".to_string()),+ owner: "user_1".to_string(),+ file_name: "name".to_string(),},);@@ -433,7 +433,6 @@ fn test_document_history_deleted() {let input_not_found = vec![create_test_document_response("doc_not_found","node_2",- "user_1",Some(vec!["stale data".to_string()]),)];@@ -442,7 +441,6 @@ fn test_document_history_deleted() {let result_not_found =construct_search_result(input_not_found, document_histories_not_found).unwrap();- // Document not in DB should be returned with metadata=None- assert_eq!(result_not_found.len(), 1);- assert!(result_not_found[0].metadata.is_none());+ // Document not in DB should not be returned+ assert_eq!(result_not_found.len(), 0);}diff --git a/rust/cloud-storage/search_service/src/api/search/email.rs b/rust/cloud-storage/search_service/src/api/search/email.rsindex 2cc58a78ba..c7d2528d4a 100644--- a/rust/cloud-storage/search_service/src/api/search/email.rs+++ b/rust/cloud-storage/search_service/src/api/search/email.rs@@ -1,6 +1,6 @@+use crate::api::ApiContext;use crate::api::search::simple::SearchError;-use crate::{api::ApiContext, util};-use crate::{api::search::simple::simple_email::search_emails, model::EmailOpenSearchResponse};+use crate::api::search::simple::simple_email::search_emails;use axum::{Extension,extract::{self, State},@@ -10,9 +10,10 @@ use axum::{use model::{response::ErrorResponse, user::UserContext};use models_email::service::message::{ThreadHistoryInfo, ThreadHistoryRequest};use models_search::email::{- EmailSearchMetadata, EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem,+ EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem,EmailSearchResponseItemWithMetadata, EmailSearchResult,};+use opensearch_client::search::model::SearchGotoContent;use sqlx::types::Uuid;use std::collections::HashMap;@@ -23,19 +24,25 @@ use super::SearchPaginationParams;pub(in crate::api::search) async fn enrich_emails(ctx: &ApiContext,user_id: &str,- results: Vec<opensearch_client::search::emails::EmailSearchResponse>,+ results: Vec<opensearch_client::search::model::SearchHit>,) -> Result<Vec<EmailSearchResponseItemWithMetadata>, SearchError> {+ let results: Vec<opensearch_client::search::model::SearchHit> = results+ .into_iter()+ .filter(|r| r.entity_type == models_opensearch::SearchEntityType::Emails)+ .collect();+if results.is_empty() {return Ok(vec![]);}+// Extract thread IDs from resultslet thread_ids: Vec<Uuid> = results.iter().filter_map(|r| {- match Uuid::parse_str(&r.thread_id) {+ match Uuid::parse_str(&r.entity_id) {Ok(uuid) => Some(uuid),Err(e) => {- tracing::warn!(error=?e, thread_id=?r.thread_id, "Failed to parse thread ID as UUID");+ tracing::warn!(error=?e, thread_id=?r.entity_id, "Failed to parse thread ID as UUID");None}}@@ -107,35 +114,69 @@ pub async fn handler(}pub fn construct_search_result(- search_results: Vec<opensearch_client::search::emails::EmailSearchResponse>,+ search_results: Vec<opensearch_client::search::model::SearchHit>,thread_histories: HashMap<Uuid, ThreadHistoryInfo>,) -> anyhow::Result<Vec<EmailSearchResponseItemWithMetadata>> {- let search_results = search_results+ // construct entity hit map of id -> vec<hits>+ let entity_id_hit_map: HashMap<Uuid, Vec<EmailSearchResult>> = search_results.into_iter()- .map(|inner| EmailOpenSearchResponse { inner })- .collect();- let result = util::construct_search_result::<- EmailOpenSearchResponse,- EmailSearchResult,- EmailSearchMetadata,- >(search_results)?;- // To preserve backwards compatibility for now, convert back into old struct- let result: Vec<EmailSearchResponseItem> = result.into_iter().map(|a| a.into()).collect();-- let result: Vec<EmailSearchResponseItemWithMetadata> = result+ .map(|hit| {+ let result = if let Some(SearchGotoContent::Emails(goto)) = hit.goto {+ EmailSearchResult {+ message_id: Some(goto.email_message_id),+ bcc: goto.bcc,+ cc: goto.cc,+ labels: goto.labels,+ sent_at: goto.sent_at,+ sender: Some(goto.sender),+ recipients: goto.recipients,+ highlight: hit.highlight.into(),+ score: hit.score,+ }+ } else {+ // name match+ EmailSearchResult {+ message_id: None,+ bcc: vec![],+ cc: vec![],+ labels: vec![],+ sent_at: None,+ sender: None,+ recipients: vec![],+ highlight: hit.highlight.into(),+ score: hit.score,+ }+ };+ (hit.entity_id.parse().unwrap(), result)+ })+ .fold(HashMap::new(), |mut map, (entity_id, result)| {+ map.entry(entity_id).or_insert_with(Vec::new).push(result);+ map+ });++ // now construct the search results+ let result: Vec<EmailSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter()- .map(|item| {- let message_uuid = Uuid::parse_str(&item.thread_id).unwrap_or_else(|_| Uuid::nil());- let message_history_info = thread_histories- .get(&message_uuid)- .cloned()- .unwrap_or_default();- EmailSearchResponseItemWithMetadata {- created_at: message_history_info.created_at.timestamp(),- updated_at: message_history_info.updated_at.timestamp(),- viewed_at: message_history_info.viewed_at.map(|a| a.timestamp()),- snippet: message_history_info.snippet,- extra: item,+ .filter_map(|(entity_id, hits)| {+ if let Some(info) = thread_histories.get(&entity_id) {+ let info = info.clone();+ Some(EmailSearchResponseItemWithMetadata {+ created_at: info.created_at.timestamp(),+ updated_at: info.updated_at.timestamp(),+ viewed_at: info.viewed_at.map(|a| a.timestamp()),+ snippet: info.snippet,+ extra: EmailSearchResponseItem {+ id: entity_id.to_string(),+ thread_id: entity_id.to_string(),+ owner_id: info.user_id.clone(),+ user_id: info.user_id,+ name: info.subject.clone(),+ subject: info.subject,+ email_message_search_results: hits,+ },+ })+ } else {+ None}}).collect();diff --git a/rust/cloud-storage/search_service/src/api/search/email/test.rs b/rust/cloud-storage/search_service/src/api/search/email/test.rsindex 910e8db819..d84b9f2e3a 100644--- a/rust/cloud-storage/search_service/src/api/search/email/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/email/test.rs@@ -1,3 +1,4 @@+use models_opensearch::SearchEntityType;use opensearch_client::search::model::Highlight;use super::*;@@ -26,19 +27,20 @@ fn test_construct_search_result_empty_input() {#[test]fn test_construct_search_result_single_thread() {let thread_uuid = "550e8400-e29b-41d4-a716-446655440000";- let search_results = vec![opensearch_client::search::emails::EmailSearchResponse {- thread_id: thread_uuid.to_string(),- message_id: "msg1".to_string(),- sender: "[email protected]".to_string(),- recipients: vec!["[email protected]".to_string()],- cc: vec![],- bcc: vec![],- labels: vec!["inbox".to_string()],- link_id: "link1".to_string(),- user_id: "user1".to_string(),- updated_at: 1234567890,- sent_at: Some(1234567800),- subject: Some("Test Subject".to_string()),+ let search_results = vec![opensearch_client::search::model::SearchHit {+ entity_id: thread_uuid.to_string(),+ entity_type: SearchEntityType::Emails,+ goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(+ opensearch_client::search::model::SearchGotoEmail {+ email_message_id: "msg1".to_string(),+ sender: "[email protected]".to_string(),+ recipients: vec!["[email protected]".to_string()],+ cc: vec![],+ bcc: vec![],+ labels: vec!["inbox".to_string()],+ sent_at: Some(1234567800),+ },+ )),score: None,highlight: Highlight {name: None,@@ -59,11 +61,11 @@ fn test_construct_search_result_single_thread() {assert_eq!(result[0].extra.user_id, "user1");assert_eq!(result[0].extra.email_message_search_results.len(), 1);assert_eq!(- result[0].extra.email_message_search_results[0].message_id,+ result[0].extra.email_message_search_results[0]+ .message_id+ .as_ref()+ .unwrap(),"msg1");- assert_eq!(- result[0].extra.email_message_search_results[0].subject,- Some("Test Subject".to_string())- );+ assert_eq!(result[0].extra.subject, Some("subject".to_string()));}diff --git a/rust/cloud-storage/search_service/src/api/search/enrich.rs b/rust/cloud-storage/search_service/src/api/search/enrich.rsindex dce8463643..83c579ce8d 100644--- a/rust/cloud-storage/search_service/src/api/search/enrich.rs+++ b/rust/cloud-storage/search_service/src/api/search/enrich.rs@@ -1,11 +1,8 @@//! This module is responsible for enriching search results with metadata+use models_opensearch::SearchEntityType;use models_search::unified::UnifiedSearchResponseItem;-use opensearch_client::search::{- channels::ChannelMessageSearchResponse, chats::ChatSearchResponse,- documents::DocumentSearchResponse, emails::EmailSearchResponse,- projects::ProjectSearchResponse,-};+use opensearch_client::search::model::SearchHit;use crate::api::{context::ApiContext,@@ -15,96 +12,48 @@ use crate::api::{},};-/// Trait to enrich the search results from opensearch with extra data-pub(super) trait EnrichSearchResponse<T>: Iterator<Item = T> {- fn enrich_search_response(- self,- ctx: &ApiContext,- user_id: &str,- ) -> impl Future<Output = Result<Vec<UnifiedSearchResponseItem>, SearchError>> + Send;-}--impl<T> EnrichSearchResponse<DocumentSearchResponse> for T-where- T: Iterator<Item = DocumentSearchResponse> + Send,-{- async fn enrich_search_response(- self,- ctx: &ApiContext,- user_id: &str,- ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {- let response = enrich_documents(ctx, user_id, self.collect()).await?;- Ok(response- .into_iter()- .map(UnifiedSearchResponseItem::Document)- .collect())- }-}--impl<T> EnrichSearchResponse<EmailSearchResponse> for T-where- T: Iterator<Item = EmailSearchResponse> + Send,-{- async fn enrich_search_response(- self,- ctx: &ApiContext,- user_id: &str,- ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {- let response = enrich_emails(ctx, user_id, self.collect()).await?;- Ok(response- .into_iter()- .map(UnifiedSearchResponseItem::Email)- .collect())- }-}--impl<T> EnrichSearchResponse<ChannelMessageSearchResponse> for T-where- T: Iterator<Item = ChannelMessageSearchResponse> + Send,-{- async fn enrich_search_response(- self,- ctx: &ApiContext,- user_id: &str,- ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {- let response = enrich_channels(ctx, user_id, self.collect()).await?;- Ok(response- .into_iter()- .map(UnifiedSearchResponseItem::Channel)- .collect())- }-}--impl<T> EnrichSearchResponse<ChatSearchResponse> for T-where- T: Iterator<Item = ChatSearchResponse> + Send,-{- async fn enrich_search_response(- self,- ctx: &ApiContext,- user_id: &str,- ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {- let response = enrich_chats(ctx, user_id, self.collect()).await?;- Ok(response- .into_iter()- .map(UnifiedSearchResponseItem::Chat)- .collect())- }-}--impl<T> EnrichSearchResponse<ProjectSearchResponse> for T-where- T: Iterator<Item = ProjectSearchResponse> + Send,-{- async fn enrich_search_response(- self,- ctx: &ApiContext,- user_id: &str,- ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {- let response = enrich_projects(ctx, user_id, self.collect()).await?;- Ok(response- .into_iter()- .map(UnifiedSearchResponseItem::Project)- .collect())+/// Enriches search results with metadat and converts to UnifiedSearchResponseItem+pub async fn enrich_search_response(+ ctx: &ApiContext,+ user_id: &str,+ results: Vec<SearchHit>,+ entity_type: SearchEntityType,+) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {+ match entity_type {+ SearchEntityType::Documents => {+ let response = enrich_documents(ctx, user_id, results).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Document)+ .collect())+ }+ SearchEntityType::Emails => {+ let response = enrich_emails(ctx, user_id, results).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Email)+ .collect())+ }+ SearchEntityType::Channels => {+ let response = enrich_channels(ctx, user_id, results).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Channel)+ .collect())+ }+ SearchEntityType::Chats => {+ let response = enrich_chats(ctx, user_id, results).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Chat)+ .collect())+ }+ SearchEntityType::Projects => {+ let response = enrich_projects(ctx, user_id, results).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Project)+ .collect())+ }}}diff --git a/rust/cloud-storage/search_service/src/api/search/project.rs b/rust/cloud-storage/search_service/src/api/search/project.rsindex 0043903fdb..2c38f1f780 100644--- a/rust/cloud-storage/search_service/src/api/search/project.rs+++ b/rust/cloud-storage/search_service/src/api/search/project.rs@@ -1,7 +1,4 @@-use crate::{- api::search::simple::{SearchError, simple_project::search_projects},- model::ProjectOpenSearchResponse,-};+use crate::api::search::simple::{SearchError, simple_project::search_projects};use axum::{Extension,extract::{self, State},@@ -10,12 +7,12 @@ use axum::{};use model::{response::ErrorResponse, user::UserContext};use models_search::project::{- ProjectSearchMetadata, ProjectSearchRequest, ProjectSearchResponse, ProjectSearchResponseItem,+ ProjectSearchRequest, ProjectSearchResponse, ProjectSearchResponseItem,ProjectSearchResponseItemWithMetadata, ProjectSearchResult,};use std::collections::HashMap;-use crate::{api::ApiContext, util};+use crate::api::ApiContext;use super::SearchPaginationParams;@@ -24,13 +21,18 @@ use super::SearchPaginationParams;pub(in crate::api::search) async fn enrich_projects(ctx: &ApiContext,user_id: &str,- results: Vec<opensearch_client::search::projects::ProjectSearchResponse>,+ results: Vec<opensearch_client::search::model::SearchHit>,) -> Result<Vec<ProjectSearchResponseItemWithMetadata>, SearchError> {+ let results: Vec<opensearch_client::search::model::SearchHit> = results+ .into_iter()+ .filter(|r| r.entity_type == models_opensearch::SearchEntityType::Projects)+ .collect();+if results.is_empty() {return Ok(vec![]);}// Extract project IDs from results- let project_ids: Vec<String> = results.iter().map(|r| r.project_id.clone()).collect();+ let project_ids: Vec<String> = results.iter().map(|r| r.entity_id.clone()).collect();// Fetch project metadata from databaselet project_histories =@@ -97,39 +99,54 @@ pub async fn handler(}pub fn construct_search_result(- search_results: Vec<opensearch_client::search::projects::ProjectSearchResponse>,+ search_results: Vec<opensearch_client::search::model::SearchHit>,project_histories: HashMap<String,macro_db_client::projects::get_project_history::ProjectHistoryInfo,>,) -> anyhow::Result<Vec<ProjectSearchResponseItemWithMetadata>> {- let search_results = search_results+ // construct entity hit map of id -> vec<hits>+ let entity_id_hit_map: HashMap<String, Vec<ProjectSearchResult>> = search_results.into_iter()- .map(|inner| ProjectOpenSearchResponse { inner })- .collect();- let result = util::construct_search_result::<- ProjectOpenSearchResponse,- ProjectSearchResult,- ProjectSearchMetadata,- >(search_results)?;- let result: Vec<ProjectSearchResponseItem> = result.into_iter().map(|a| a.into()).collect();- // Add metadata for each project, fetched from macrodb- let result: Vec<ProjectSearchResponseItemWithMetadata> = result+ .map(|hit| {+ let result = ProjectSearchResult {+ highlight: hit.highlight.into(),+ score: hit.score,+ };++ (hit.entity_id, result)+ })+ .fold(HashMap::new(), |mut map, (entity_id, result)| {+ map.entry(entity_id).or_insert_with(Vec::new).push(result);+ map+ });++ // now construct the search results+ let result: Vec<ProjectSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter()- .map(|item| {- let metadata = project_histories.get(&item.id).map(|info| {- models_search::project::ProjectMetadata {+ .filter_map(|(entity_id, hits)| {+ if let Some(info) = project_histories.get(&entity_id) {+ let info = info.clone();+ let metadata = models_search::project::ProjectMetadata {created_at: info.created_at.timestamp(),updated_at: info.updated_at.timestamp(),viewed_at: info.viewed_at.map(|a| a.timestamp()),parent_project_id: info.parent_project_id.clone(),deleted_at: info.deleted_at.map(|a| a.timestamp()),- }- });-- ProjectSearchResponseItemWithMetadata {- metadata,- extra: item,+ };+ Some(ProjectSearchResponseItemWithMetadata {+ metadata: Some(metadata),+ extra: ProjectSearchResponseItem {+ id: entity_id.clone(),+ owner_id: info.user_id.clone(),+ name: info.name,+ project_search_results: hits,+ updated_at: info.updated_at.timestamp(),+ created_at: info.created_at.timestamp(),+ },+ })+ } else {+ None}}).collect();diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rsindex 49309925dd..a3e48e9264 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs@@ -5,11 +5,13 @@ use std::collections::HashSet;use axum::{Extension,extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},+ response::Json,};use model::{response::ErrorResponse, user::UserContext};-use models_search::channel::{ChannelSearchRequest, SimpleChannelSearchResponse};+use models_search::{+ SimpleSearchResponse,+ channel::{ChannelSearchRequest, SimpleChannelSearchResponse},+};use opensearch_client::search::channels::ChannelMessageSearchArgs;use crate::api::ApiContext;@@ -37,7 +39,7 @@ pub async fn handler(user_context: Extension<UserContext>,extract::Query(query_params): extract::Query<SearchPaginationParams>,extract::Json(req): extract::Json<ChannelSearchRequest>,-) -> Result<Response, SearchError> {+) -> Result<Json<SimpleSearchResponse>, SearchError> {tracing::info!("simple_channel_search");let results = search_channels(@@ -49,13 +51,9 @@ pub async fn handler().await?;- Ok((- StatusCode::OK,- Json(SimpleChannelSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }),- )- .into_response())+ Ok(Json(SimpleSearchResponse {+ results: results.into_iter().map(|a| a.into()).collect(),+ }))}pub(in crate::api::search) struct FilterChannelResponse {@@ -115,7 +113,7 @@ pub(in crate::api::search) async fn search_channels(organization_id: Option<i32>,query_params: &SearchPaginationParams,req: ChannelSearchRequest,-) -> Result<Vec<opensearch_client::search::channels::ChannelMessageSearchResponse>, SearchError> {+) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {if user_id.is_empty() {return Err(SearchError::NoUserId);}diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rsindex 94e5c47814..a56d64c426 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs@@ -2,8 +2,7 @@ use crate::api::search::{SearchPaginationParams, simple::SearchError};use axum::{Extension,extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},+ response::Json,};use item_filters::ChatFilters;use model::{@@ -11,7 +10,10 @@ use model::{response::ErrorResponse,user::UserContext,};-use models_search::chat::{ChatSearchRequest, SimpleChatSearchResponse};+use models_search::{+ SimpleSearchResponse,+ chat::{ChatSearchRequest, SimpleChatSearchResponse},+};use opensearch_client::search::chats::ChatSearchArgs;use crate::api::ApiContext;@@ -39,18 +41,14 @@ pub async fn handler(user_context: Extension<UserContext>,extract::Query(query_params): extract::Query<SearchPaginationParams>,extract::Json(req): extract::Json<ChatSearchRequest>,-) -> Result<Response, SearchError> {+) -> Result<Json<SimpleSearchResponse>, SearchError> {tracing::info!("simple_chat_search");let results = search_chats(&ctx, user_context.user_id.as_str(), &query_params, req).await?;- Ok((- StatusCode::OK,- Json(SimpleChatSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }),- )- .into_response())+ Ok(Json(SimpleSearchResponse {+ results: results.into_iter().map(|a| a.into()).collect(),+ }))}pub(in crate::api::search) struct FilterChatResponse {@@ -148,7 +146,7 @@ pub(in crate::api::search) async fn search_chats(user_id: &str,query_params: &SearchPaginationParams,req: ChatSearchRequest,-) -> Result<Vec<opensearch_client::search::chats::ChatSearchResponse>, SearchError> {+) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {if user_id.is_empty() {return Err(SearchError::NoUserId);}diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rsindex 73590f2286..c56fce41c6 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs@@ -2,8 +2,7 @@ use crate::api::search::{SearchPaginationParams, simple::SearchError};use axum::{Extension,extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},+ response::Json,};use item_filters::DocumentFilters;use model::{@@ -11,7 +10,10 @@ use model::{response::ErrorResponse,user::UserContext,};-use models_search::document::{DocumentSearchRequest, SimpleDocumentSearchResponse};+use models_search::{+ SimpleSearchResponse,+ document::{DocumentSearchRequest, SimpleDocumentSearchResponse},+};use opensearch_client::search::documents::DocumentSearchArgs;use crate::api::ApiContext;@@ -39,18 +41,14 @@ pub async fn handler(user_context: Extension<UserContext>,extract::Query(query_params): extract::Query<SearchPaginationParams>,extract::Json(req): extract::Json<DocumentSearchRequest>,-) -> Result<Response, SearchError> {+) -> Result<Json<SimpleSearchResponse>, SearchError> {tracing::info!("simple_document_search");let results = search_documents(&ctx, user_context.user_id.as_str(), &query_params, req).await?;- Ok((- StatusCode::OK,- Json(SimpleDocumentSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }),- )- .into_response())+ Ok(Json(SimpleSearchResponse {+ results: results.into_iter().map(|a| a.into()).collect(),+ }))}pub(in crate::api::search) struct FilterDocumentResponse {@@ -176,7 +174,7 @@ pub(in crate::api::search) async fn search_documents(user_id: &str,query_params: &SearchPaginationParams,req: DocumentSearchRequest,-) -> Result<Vec<opensearch_client::search::documents::DocumentSearchResponse>, SearchError> {+) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {if user_id.is_empty() {return Err(SearchError::NoUserId);}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.rsindex eda24ea48c..4d13e4e8d7 100644--- 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@@ -2,11 +2,13 @@ use crate::api::search::{SearchPaginationParams, simple::SearchError};use axum::{Extension,extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},+ response::Json,};use model::{response::ErrorResponse, user::UserContext};-use models_search::email::{EmailSearchRequest, SimpleEmailSearchResponse};+use models_search::{+ SimpleSearchResponse,+ email::{EmailSearchRequest, SimpleEmailSearchResponse},+};use opensearch_client::search::emails::EmailSearchArgs;use crate::api::ApiContext;@@ -34,18 +36,14 @@ pub async fn handler(user_context: Extension<UserContext>,extract::Query(query_params): extract::Query<SearchPaginationParams>,extract::Json(req): extract::Json<EmailSearchRequest>,-) -> Result<Response, SearchError> {+) -> Result<Json<SimpleSearchResponse>, SearchError> {tracing::info!("simple_email_search");let results = search_emails(&ctx, user_context.user_id.as_str(), &query_params, req).await?;- Ok((- StatusCode::OK,- Json(SimpleEmailSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }),- )- .into_response())+ Ok(Json(SimpleSearchResponse {+ results: results.into_iter().map(|a| a.into()).collect(),+ }))}pub(in crate::api::search) async fn search_emails(@@ -53,7 +51,7 @@ pub(in crate::api::search) async fn search_emails(user_id: &str,query_params: &SearchPaginationParams,req: EmailSearchRequest,-) -> Result<Vec<opensearch_client::search::emails::EmailSearchResponse>, SearchError> {+) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {if user_id.is_empty() {return Err(SearchError::NoUserId);}diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rsindex 80f864c875..80dae536bb 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs@@ -2,8 +2,7 @@ use crate::api::search::{SearchPaginationParams, simple::SearchError};use axum::{Extension,extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},+ response::Json,};use item_filters::ProjectFilters;use model::{@@ -11,8 +10,8 @@ use model::{response::ErrorResponse,user::UserContext,};-use models_search::SearchOn;use models_search::project::{ProjectSearchRequest, SimpleProjectSearchResponse};+use models_search::{SearchOn, SimpleSearchResponse};use opensearch_client::search::projects::ProjectSearchArgs;use crate::api::ApiContext;@@ -40,18 +39,14 @@ pub async fn handler(user_context: Extension<UserContext>,extract::Query(query_params): extract::Query<SearchPaginationParams>,extract::Json(req): extract::Json<ProjectSearchRequest>,-) -> Result<Response, SearchError> {+) -> Result<Json<SimpleSearchResponse>, SearchError> {tracing::info!("simple_project_search");let results = search_projects(&ctx, user_context.user_id.as_str(), &query_params, req).await?;- Ok((- StatusCode::OK,- Json(SimpleProjectSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }),- )- .into_response())+ Ok(Json(SimpleSearchResponse {+ results: results.into_iter().map(|a| a.into()).collect(),+ }))}pub(in crate::api::search) struct FilterProjectResponse {@@ -147,7 +142,7 @@ pub(in crate::api::search) async fn search_projects(user_id: &str,query_params: &SearchPaginationParams,req: ProjectSearchRequest,-) -> Result<Vec<opensearch_client::search::projects::ProjectSearchResponse>, SearchError> {+) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {// content search is not applicable for projectsif req.search_on == SearchOn::Content {return Ok(Vec::new());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.rsindex fb5916b011..a9999715b2 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@@ -14,9 +14,12 @@ use axum::{response::Json,};use model::{response::ErrorResponse, user::UserContext};-use models_search::unified::{- SimpleUnifiedSearchResponse, UnifiedSearchIndex, UnifiedSearchRequest,- generate_unified_search_indices,+use models_search::{+ SimpleSearchResponse,+ unified::{+ SimpleUnifiedSearchResponse, UnifiedSearchIndex, UnifiedSearchRequest,+ generate_unified_search_indices,+ },};use opensearch_client::search::unified::UnifiedSearchArgs;@@ -28,7 +31,7 @@ pub(in crate::api::search) async fn perform_unified_search(user_context: &UserContext,query_params: SearchPaginationParams,req: UnifiedSearchRequest,-) -> Result<Vec<opensearch_client::search::unified::UnifiedSearchResponse>, SearchError> {+) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {let user_id = &user_context.user_id;let user_organization_id = user_context.organization_id;let search_on = req.search_on;@@ -188,12 +191,12 @@ pub async fn handler(user_context: Extension<UserContext>,extract::Query(query_params): extract::Query<SearchPaginationParams>,extract::Json(req): extract::Json<UnifiedSearchRequest>,-) -> Result<Json<SimpleUnifiedSearchResponse>, SearchError> {+) -> Result<Json<SimpleSearchResponse>, SearchError> {tracing::info!("simple_unified_search");let results = perform_unified_search(&ctx, &user_context, query_params, req).await?;let results = results.into_iter().map(|a| a.into()).collect();- Ok(Json(SimpleUnifiedSearchResponse { results }))+ Ok(Json(SimpleSearchResponse { results }))}diff --git a/rust/cloud-storage/search_service/src/api/search/unified.rs b/rust/cloud-storage/search_service/src/api/search/unified.rsindex 705010b545..7332b8b6f8 100644--- a/rust/cloud-storage/search_service/src/api/search/unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/unified.rs@@ -2,7 +2,7 @@ use super::SearchPaginationParams;use crate::api::{ApiContext,search::{- enrich::EnrichSearchResponse,+ enrich::enrich_search_response,simple::{SearchError, simple_unified::perform_unified_search},},};@@ -45,6 +45,7 @@ pub async fn handler(let results = perform_unified_search(&ctx, &user_context, query_params, req).await?;+ // Split the results by entity typelet SplitUnifiedSearchResponseValues {channel_message,chat,@@ -60,20 +61,36 @@ pub async fn handler(enriched_project_results,enriched_email_results,) = tokio::try_join!(- document- .into_iter()- .enrich_search_response(&ctx, &user_context.user_id),- chat.into_iter()- .enrich_search_response(&ctx, &user_context.user_id),- channel_message- .into_iter()- .enrich_search_response(&ctx, &user_context.user_id),- project- .into_iter()- .enrich_search_response(&ctx, &user_context.user_id),- .into_iter()- .enrich_search_response(&ctx, &user_context.user_id)+ enrich_search_response(+ &ctx,+ &user_context.user_id,+ document,+ models_opensearch::SearchEntityType::Documents+ ),+ enrich_search_response(+ &ctx,+ &user_context.user_id,+ chat,+ models_opensearch::SearchEntityType::Chats+ ),+ enrich_search_response(+ &ctx,+ &user_context.user_id,+ channel_message,+ models_opensearch::SearchEntityType::Channels+ ),+ enrich_search_response(+ &ctx,+ &user_context.user_id,+ project,+ models_opensearch::SearchEntityType::Projects+ ),+ enrich_search_response(+ &ctx,+ &user_context.user_id,+ email,+ models_opensearch::SearchEntityType::Emails+ ),).map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;diff --git a/rust/cloud-storage/search_service/src/main.rs b/rust/cloud-storage/search_service/src/main.rsindex 461d9e2e58..80c11752ab 100644--- a/rust/cloud-storage/search_service/src/main.rs+++ b/rust/cloud-storage/search_service/src/main.rs@@ -14,8 +14,6 @@ use std::sync::Arc;mod api;mod config;-mod model;-mod util;#[tokio::main]async fn main() -> anyhow::Result<()> {diff --git a/rust/cloud-storage/search_service/src/model/mod.rs b/rust/cloud-storage/search_service/src/model/mod.rsdeleted file mode 100644index 8bde0a179e..0000000000--- a/rust/cloud-storage/search_service/src/model/mod.rs+++ /dev/null@@ -1,195 +0,0 @@-use models_search::{- ItemId, Metadata,- channel::{ChannelSearchMetadata, ChannelSearchResult},- chat::{ChatMessageSearchResult, ChatSearchMetadata},- document::{DocumentSearchMetadata, DocumentSearchResult},- email::{EmailSearchMetadata, EmailSearchResult},- project::{ProjectSearchMetadata, ProjectSearchResult},-};-use opensearch_client::search::{- channels::ChannelMessageSearchResponse, chats::ChatSearchResponse,- documents::DocumentSearchResponse, emails::EmailSearchResponse,- projects::ProjectSearchResponse,-};--/// Response from OpenSearch for individual chat search results-#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct ChatOpenSearchResponse {- pub inner: ChatSearchResponse,-}--impl ItemId for ChatOpenSearchResponse {- fn get_id(&self) -> &String {- &self.inner.chat_id- }-}--impl From<&ChatOpenSearchResponse> for Option<ChatMessageSearchResult> {- fn from(response: &ChatOpenSearchResponse) -> Self {- Some(ChatMessageSearchResult {- chat_message_id: response.inner.chat_message_id.clone(),- role: response.inner.role.clone(),- highlight: response.inner.highlight.clone().into(),- updated_at: response.inner.updated_at,- title: response.inner.title.clone(),- score: response.inner.score,- })- }-}--impl Metadata<ChatSearchMetadata> for ChatOpenSearchResponse {- fn metadata(&self, id: &str) -> ChatSearchMetadata {- ChatSearchMetadata {- chat_id: id.to_string(),- user_id: self.inner.user_id.clone(),- title: self.inner.title.clone(),- }- }-}--/// Response from OpenSearch for individual project search results-#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct ProjectOpenSearchResponse {- pub inner: ProjectSearchResponse,-}--impl ItemId for ProjectOpenSearchResponse {- fn get_id(&self) -> &String {- &self.inner.project_id- }-}--impl Metadata<ProjectSearchMetadata> for ProjectOpenSearchResponse {- fn metadata(&self, id: &str) -> ProjectSearchMetadata {- ProjectSearchMetadata {- project_id: id.to_string(),- updated_at: self.inner.updated_at,- created_at: self.inner.created_at,- project_name: self.inner.project_name.clone(),- owner_id: self.inner.user_id.clone(),- }- }-}--impl From<&ProjectOpenSearchResponse> for Option<ProjectSearchResult> {- fn from(response: &ProjectOpenSearchResponse) -> Self {- Some(ProjectSearchResult {- highlight: response.inner.highlight.clone().into(),- score: response.inner.score,- })- }-}-// Document--/// Response from OpenSearch for individual document search results-#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct DocumentOpenSearchResponse {- pub inner: DocumentSearchResponse,-}--impl Metadata<DocumentSearchMetadata> for DocumentOpenSearchResponse {- fn metadata(&self, id: &str) -> DocumentSearchMetadata {- DocumentSearchMetadata {- document_id: id.to_string(),- document_name: self.inner.document_name.clone(),- owner_id: self.inner.owner_id.clone(),- file_type: self.inner.file_type.clone(),- }- }-}--impl ItemId for DocumentOpenSearchResponse {- fn get_id(&self) -> &String {- &self.inner.document_id- }-}--impl From<&DocumentOpenSearchResponse> for Option<DocumentSearchResult> {- fn from(response: &DocumentOpenSearchResponse) -> Self {- Some(DocumentSearchResult {- node_id: response.inner.node_id.clone(),- raw_content: response.inner.raw_content.clone(),- updated_at: response.inner.updated_at,- highlight: response.inner.highlight.clone().into(),- score: response.inner.score,- })- }-}---/// Response from OpenSearch for individual email search results-#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct EmailOpenSearchResponse {- pub inner: EmailSearchResponse,-}--impl Metadata<EmailSearchMetadata> for EmailOpenSearchResponse {- fn metadata(&self, id: &str) -> EmailSearchMetadata {- EmailSearchMetadata {- thread_id: id.to_string(),- user_id: self.inner.user_id.clone(),- }- }-}--impl ItemId for EmailOpenSearchResponse {- fn get_id(&self) -> &String {- &self.inner.thread_id- }-}--impl From<&EmailOpenSearchResponse> for Option<EmailSearchResult> {- fn from(response: &EmailOpenSearchResponse) -> Self {- Some(EmailSearchResult {- message_id: response.inner.message_id.clone(),- subject: response.inner.subject.clone(),- sender: response.inner.sender.clone(),- recipients: response.inner.recipients.clone(),- cc: response.inner.cc.clone(),- bcc: response.inner.bcc.clone(),- labels: response.inner.labels.clone(),- highlight: response.inner.highlight.clone().into(),- updated_at: response.inner.updated_at,- sent_at: response.inner.sent_at,- score: response.inner.score,- })- }-}--// Channel--/// Response from OpenSearch for individual email search results-#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct ChannelOpenSearchResponse {- pub inner: ChannelMessageSearchResponse,-}--impl Metadata<ChannelSearchMetadata> for ChannelOpenSearchResponse {- fn metadata(&self, id: &str) -> ChannelSearchMetadata {- ChannelSearchMetadata {- channel_id: id.to_string(),- channel_type: self.inner.channel_type.clone(),- }- }-}--impl ItemId for ChannelOpenSearchResponse {- fn get_id(&self) -> &String {- &self.inner.channel_id- }-}--impl From<&ChannelOpenSearchResponse> for Option<ChannelSearchResult> {- fn from(response: &ChannelOpenSearchResponse) -> Self {- Some(ChannelSearchResult {- message_id: response.inner.message_id.clone(),- thread_id: response.inner.thread_id.clone(),- sender_id: response.inner.sender_id.clone(),- highlight: response.inner.highlight.clone().into(),- updated_at: response.inner.updated_at,- created_at: response.inner.created_at,- score: response.inner.score,- })- }-}diff --git a/rust/cloud-storage/search_service/src/util/mod.rs b/rust/cloud-storage/search_service/src/util/mod.rsdeleted file mode 100644index 696e510941..0000000000--- a/rust/cloud-storage/search_service/src/util/mod.rs+++ /dev/null@@ -1,253 +0,0 @@-use models_search::{ItemId, Metadata, SearchResponseItem};-use std::collections::BTreeMap;--/// Key struct that encodes rank for proper BTreeMap ordering.-/// Items are ordered first by rank, then by ID as tiebreaker.-#[derive(Debug, Clone, PartialEq, Eq)]-struct RankedKey {- rank: u64,- id: String,-}--impl Ord for RankedKey {- fn cmp(&self, other: &Self) -> std::cmp::Ordering {- self.rank- .cmp(&other.rank)- .then_with(|| self.id.cmp(&other.id))- }-}--impl PartialOrd for RankedKey {- fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {- Some(self.cmp(other))- }-}--type SearchResultsMap<T> = BTreeMap<RankedKey, Vec<T>>;--fn build_search_results_map<T>(search_results: Vec<T>) -> SearchResultsMap<T>-where- T: ItemId,-{- let mut search_results_map: SearchResultsMap<T> = BTreeMap::new();- let mut rank = 0;- let mut id_to_rank = std::collections::HashMap::new();-- // Assign ranks based on first appearance- for result in &search_results {- let id = result.get_id();- if !id_to_rank.contains_key(id) {- id_to_rank.insert(id.clone(), rank);- let ranked_key = RankedKey {- rank,- id: id.clone(),- };- search_results_map.insert(ranked_key, vec![]);- rank += 1;- }- }-- // Populate with results- for result in search_results {- let id = result.get_id();- let rank = id_to_rank[id];- let ranked_key = RankedKey {- rank,- id: id.clone(),- };- search_results_map- .get_mut(&ranked_key)- .unwrap()- .push(result);- }-- search_results_map-}--fn build_search_results<T, U, V>(- search_results_map: SearchResultsMap<T>,-) -> Vec<SearchResponseItem<U, V>>-where- Option<U>: for<'a> From<&'a T>,- T: Metadata<V>,-{- let mut result = vec![];-- for (ranked_key, search_results) in search_results_map {- if search_results.is_empty() {- tracing::warn!("no search results found for id {}", ranked_key.id);- continue;- }-- let base_search_result = &search_results[0];-- let filtered_results: Vec<U> = search_results- .iter()- .filter_map(|result| result.into())- .collect();-- let metadata: V = base_search_result.metadata(&ranked_key.id);-- let response_item = SearchResponseItem {- results: filtered_results,- metadata,- };-- result.push(response_item);- }-- result-}--pub fn construct_search_result<T, U, V>(- search_results: Vec<T>,-) -> anyhow::Result<Vec<SearchResponseItem<U, V>>>-where- T: ItemId + Metadata<V>,- Option<U>: for<'a> From<&'a T>,-{- let search_results_map = build_search_results_map(search_results);- let result = build_search_results(search_results_map);- Ok(result)-}--#[cfg(test)]-mod tests {- use super::*;- use models_search::{ItemId, Metadata};-- #[derive(Clone, Debug, PartialEq)]- struct TestItem {- id: String,- data: String,- }-- #[derive(Clone, Debug, PartialEq)]- struct TestMetadata {- value: String,- }-- #[derive(Clone, Debug, PartialEq)]- struct TestResult {- content: String,- }-- impl ItemId for TestItem {- fn get_id(&self) -> &String {- &self.id- }- }-- impl Metadata<TestMetadata> for TestItem {- fn metadata(&self, _id: &str) -> TestMetadata {- TestMetadata {- value: self.data.clone(),- }- }- }-- impl<'a> From<&'a TestItem> for Option<TestResult> {- fn from(item: &'a TestItem) -> Self {- Some(TestResult {- content: item.data.clone(),- })- }- }-- #[test]- fn test_construct_search_result_deterministic_output() {- // This test is expected to fail due to HashMap iteration order being non-deterministic- let search_results = vec![- TestItem {- id: "item1".to_string(),- data: "data1".to_string(),- },- TestItem {- id: "item2".to_string(),- data: "data2".to_string(),- },- TestItem {- id: "item3".to_string(),- data: "data3".to_string(),- },- ];-- // Run the function multiple times with identical inputs- let result1 = construct_search_result(search_results.clone()).unwrap();- let result2 = construct_search_result(search_results.clone()).unwrap();- let result3 = construct_search_result(search_results.clone()).unwrap();-- // Extract the order of metadata values to compare- let order1: Vec<String> = result1- .iter()- .map(|item| item.metadata.value.clone())- .collect();- let order2: Vec<String> = result2- .iter()- .map(|item| item.metadata.value.clone())- .collect();- let order3: Vec<String> = result3- .iter()- .map(|item| item.metadata.value.clone())- .collect();-- // This assertion should fail due to non-deterministic HashMap iteration order- // The items may appear in different orders in the results- assert_eq!(- order1, order2,- "Results should be identical for identical inputs (run 1 vs 2)"- );- assert_eq!(- order2, order3,- "Results should be identical for identical inputs (run 2 vs 3)"- );- assert_eq!(- order1, order3,- "Results should be identical for identical inputs (run 1 vs 3)"- );- }-- #[test]- fn test_construct_search_result_preserves_input_ranking() {- // Test that the ordering of output matches the ranking from input order- let search_results = vec![- TestItem {- id: "first".to_string(),- data: "first_data".to_string(),- },- TestItem {- id: "second".to_string(),- data: "second_data".to_string(),- },- TestItem {- id: "third".to_string(),- data: "third_data".to_string(),- },- TestItem {- id: "fourth".to_string(),- data: "fourth_data".to_string(),- },- ];-- let result = construct_search_result(search_results).unwrap();-- // Extract the order of metadata values from the result- let output_order: Vec<String> = result- .iter()- .map(|item| item.metadata.value.clone())- .collect();-- // The output should preserve the input ordering- let expected_order = vec![- "first_data".to_string(),- "second_data".to_string(),- "third_data".to_string(),- "fourth_data".to_string(),- ];-- assert_eq!(- output_order, expected_order,- "Output ordering should match input ranking order"- );- }-}