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): support name content search
Will Hutchinson1ff10491c777
diff --git a/docker-compose.yml b/docker-compose.ymlindex 2e92171360..1e3553fa22 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -17,7 +17,6 @@ services:- ./database/Clear.sql:/etc/Clear.sqlnetworks:- macro_api_network-macrocache:image: 'redis/redis-stack:latest'container_name: macrocachediff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 8c5b0ec803..ec1baaa81f 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5630,9 +5630,9 @@ dependencies = [[[package]]name = "opensearch_query_builder"-version = "0.0.5"+version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "376e68af6942eb6e32f6a3015a25fd7d63643c3d3eb8b7f03927f6b768ddb6d3"+checksum = "2729a66d99a0d14cbda2d04888b5315c2312980558021e924a1a4690fdaa36b0"dependencies = ["serde","serde_json",diff --git a/rust/cloud-storage/opensearch_client/Cargo.toml b/rust/cloud-storage/opensearch_client/Cargo.tomlindex 58863a9c76..2faf8a1322 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.0.5", default-features = false }+opensearch_query_builder = { version = "0.1.0", default-features = false }serde = { workspace = true }serde_json = { workspace = true }thiserror = { workspace = true }diff --git a/rust/cloud-storage/opensearch_client/src/error.rs b/rust/cloud-storage/opensearch_client/src/error.rsindex d8934e3b68..45ca0cf073 100644--- a/rust/cloud-storage/opensearch_client/src/error.rs+++ b/rust/cloud-storage/opensearch_client/src/error.rs@@ -3,7 +3,7 @@ use opensearch::{http::{StatusCode, response::Response},};-#[derive(thiserror::Error, Debug, serde::Serialize)]+#[derive(thiserror::Error, Debug, serde::Serialize, PartialEq)]#[serde(tag = "type")]pub enum OpensearchClientError {#[error("error deserializing response body. method: {method:?} details: {details}")]@@ -11,6 +11,11 @@ pub enum OpensearchClientError {details: String,method: Option<String>,},+ #[error("unable to serialize into json. method: {method:?} details: {details}")]+ SerializationFailed {+ details: String,+ method: Option<String>,+ },#[error("a network error occurred. status_code: {status_code} message: {message}")]NetworkError { status_code: u16, message: String },@@ -20,6 +25,9 @@ pub enum OpensearchClientError {#[error("validation failed: {details}")]ValidationFailed { details: String },+ #[error("no terms provided")]+ NoTermsProvided,+#[error("an unknown error occurred. method: {method:?} details: {details}")]Unknown {details: String,diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rsindex f826c59a6d..2220db6332 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs@@ -1,9 +1,13 @@+use crate::Result;use crate::SearchOn;-use crate::{Result, search::query::Keys, search::query::build_top_level_bool};+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 opensearch_query_builder::*;-use serde_json::{Map, Value};-/// A macro for generating delegation methods that forward calls to an inner field/// and return Self to maintain builder pattern chainability.///@@ -52,58 +56,53 @@ pub trait SearchQueryConfig {/// Content fieldconst CONTENT_KEY: &'static str = "content";- /// Override this method if you need custom sorting logic- fn default_sort() -> Value {- serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- ])+ /// 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> {+ vec![SortType::Field(FieldSort::new(+ "updated_at_seconds",+ SortOrder::Desc,+ ))]}/// Override this method if you need custom highlight logic- fn default_highlight() -> Value {- serde_json::json!({- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- })+ fn default_highlight() -> Highlight {+ Highlight::new().require_field_match(true).field(+ "content",+ HighlightField::new()+ .highlight_type("unified")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(500),+ )}}#[derive(Default)]pub struct SearchQueryBuilder<T: SearchQueryConfig> {/// The terms to search for- terms: Vec<String>,+ pub terms: Vec<String>,/// The match type to use when searching/// Defaults to "exact"- match_type: String,+ pub match_type: String,/// The page number to start at/// Defaults to 0- page: i64,+ pub page: u32,/// The page size to use/// Defaults to 10- page_size: i64,+ pub page_size: u32,/// The user id to search for- user_id: String,+ pub user_id: String,/// Fields to search on (Name, Content, NameContent). Defaults to Content- search_on: SearchOn,+ pub search_on: SearchOn,/// Whether to collapse the results to be a single result per ID_KEY/// Defaults to false.- collapse: bool,+ pub collapse: bool,/// If true, only search over the set of ids instead of ids + user_id./// Defaults to false.- ids_only: bool,+ pub ids_only: bool,/// The ids to search for defaults to an empty vector- ids: Vec<String>,+ pub ids: Vec<String>,_phantom: std::marker::PhantomData<T>,}@@ -129,12 +128,12 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {self}- pub fn page(mut self, page: i64) -> Self {+ pub fn page(mut self, page: u32) -> Self {self.page = page;self}- pub fn page_size(mut self, page_size: i64) -> Self {+ pub fn page_size(mut self, page_size: u32) -> Self {self.page_size = page_size;self}@@ -164,142 +163,178 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {self}- pub fn query_builder(&self) -> Result<BoolQueryBuilder> {- let keys = Keys {- id_key: T::ID_KEY,- user_id_key: T::USER_ID_KEY,- title_key: T::TITLE_KEY,- content_key: T::CONTENT_KEY,- };+ /// Builds the core bool query which contains all core "should" and "must" clauses+ pub fn build_bool_query(&self) -> Result<BoolQueryBuilder> {+ let mut bool_query = BoolQueryBuilder::new();- build_top_level_bool(- &self.terms,- &self.match_type,- keys,- &self.ids,- &self.user_id,- self.search_on,- self.ids_only,- )+ // 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 term_must_array: Vec<QueryType> = self.build_must_term_query()?;++ tracing::trace!("term_must_array: {:?}", term_must_array);++ // 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, 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(T::USER_ID_KEY, self.user_id.clone()));+ }++ Ok(bool_query)}- pub fn build_with_query(self, query_object: QueryType) -> Result<Value> {- let query_object = query_object.to_json();- let from = self.page * self.page_size;-- let mut query_map = Map::new();- query_map.insert("query".to_string(), query_object);- query_map.insert("from".to_string(), serde_json::json!(from));- query_map.insert("size".to_string(), serde_json::json!(self.page_size));- query_map.insert("sort".to_string(), T::default_sort());- query_map.insert("highlight".to_string(), T::default_highlight());-- // If collapse is true or searching only on Name, collapse the id field to remove duplicate- // results for pagination- if self.collapse || self.search_on == SearchOn::Name {- query_map.insert(- "collapse".to_string(),- serde_json::json!({ "field": T::ID_KEY }),+ /// 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) -> Result<SearchRequest> {+ let mut search_request = SearchRequestBuilder::new();++ // Collapse on the ID_KEY if collapse is true+ // or if we are searchign on Name or NameContent+ if self.collapse+ || self.search_on == SearchOn::Name+ || self.search_on == SearchOn::NameContent+ {+ search_request.collapse(Collapse::new(T::ID_KEY));+ }++ // We need to set the sort and highlight and any aggs depending on the search_on+ let sort_types = match self.search_on {+ SearchOn::Name | SearchOn::Content => T::default_sort_types(),+ SearchOn::NameContent => {+ vec![+ SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),+ SortType::Field(FieldSort::new(T::ID_KEY, SortOrder::Asc)),+ ]+ }+ };++ let highlight = match self.search_on {+ SearchOn::Content => T::default_highlight(),+ SearchOn::Name => Highlight::new().require_field_match(true).field(+ T::TITLE_KEY,+ HighlightField::new()+ .highlight_type("unified")+ .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("unified")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(1),+ )+ .field(+ T::CONTENT_KEY,+ HighlightField::new()+ .highlight_type("unified")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(1),+ ),+ };++ search_request.highlight(highlight);+ search_request.set_sorts(sort_types);++ search_request.from(self.page * self.page_size);+ search_request.size(self.page_size);++ let built_query: QueryType = match self.search_on {+ SearchOn::Name | SearchOn::Content => query_object.into(),+ SearchOn::NameContent => {+ 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".to_string(),+ origin: Some("now".into()),+ scale: "21d".to_string(),+ offset: Some("3d".to_string()),+ 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()+ }+ };++ // We need to add aggregration and tracking to the query if we are searching on NameContent+ if self.search_on == SearchOn::NameContent {+ search_request.track_total_hits(true);+ search_request.add_agg(+ "total_uniques".to_string(),+ AggregationType::Cardinality(CardinalityAggregation::new(T::ID_KEY)),);}- Ok(Value::Object(query_map))+ search_request.query(built_query);++ Ok(search_request.build())}-}-#[cfg(test)]-mod tests {- use super::*;+ /// 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>> {+ let keys = Keys {+ title_key: T::TITLE_KEY,+ content_key: T::CONTENT_KEY,+ };- struct TestSearchConfig;+ if self.terms.is_empty() {+ return Err(OpensearchClientError::NoTermsProvided);+ }- impl SearchQueryConfig for TestSearchConfig {- const ID_KEY: &'static str = "test_id";- const INDEX: &'static str = "test_index";- const USER_ID_KEY: &'static str = "test_user_id";- const TITLE_KEY: &'static str = "test_title";- }+ let query_key = QueryKey::from_match_type(&self.match_type)?;++ let mut must_array = Vec::new();- #[test]- fn test_search_query_builder_build() {- let terms = vec!["search".to_string(), "term".to_string()];- let ids = vec!["id1".to_string(), "id2".to_string()];- let user_id = "user123";- let page = 1;- let page_size = 20;-- let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms.clone())- .match_type("exact")- .page(page)- .page_size(page_size)- .user_id(user_id)- .ids(ids.clone());-- let query = builder.query_builder().unwrap().build();- let result = builder.build_with_query(query).unwrap();-- // Verify the structure contains expected keys- assert!(result.get("query").is_some());- assert!(result.get("from").is_some());- assert!(result.get("size").is_some());- assert!(result.get("sort").is_some());- assert!(result.get("highlight").is_some());-- // Verify pagination values- assert_eq!(result["from"], serde_json::json!(page * page_size));- assert_eq!(result["size"], serde_json::json!(page_size));-- // Verify sort structure (using default)- let expected_sort = serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- ]);- assert_eq!(result["sort"], expected_sort);-- // Verify highlight structure (using default)- let expected_highlight = serde_json::json!({- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }+ match self.search_on {+ SearchOn::Name => {+ // map all terms over title key+ must_array.push(generate_terms_must_query(+ query_key,+ &[keys.title_key],+ &self.terms,+ ));}- });- assert_eq!(result["highlight"], expected_highlight);-- // Verify query structure contains bool query- assert!(result["query"]["bool"].is_object());-- // Verify should clause contains user_id and ids terms- let should_clause = &result["query"]["bool"]["should"];- assert!(should_clause.is_array());-- let should_array = should_clause.as_array().unwrap();- assert_eq!(should_array.len(), 2);-- // Check for user_id term- let user_term_found = should_array.iter().any(|item| {- item.get("term")- .and_then(|t| t.get("test_user_id"))- .map(|v| v == user_id)- .unwrap_or(false)- });- assert!(user_term_found);-- // Check for ids terms- let ids_term_found = should_array.iter().any(|item| {- item.get("terms")- .and_then(|t| t.get("test_id"))- .and_then(|v| v.as_array())- .map(|arr| arr.len() == 2)- .unwrap_or(false)- });- assert!(ids_term_found);+ SearchOn::Content => {+ // map all terms over content key+ must_array.push(generate_terms_must_query(+ query_key,+ &[keys.content_key],+ &self.terms,+ ));+ }+ SearchOn::NameContent => {+ must_array.push(generate_name_content_query(&keys, &self.terms));+ }+ };++ Ok(must_array)}}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rsnew file mode 100644index 0000000000..a0004d925f--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs@@ -0,0 +1,548 @@+use super::*;++use opensearch_query_builder::ToOpenSearchJson;++struct TestSearchConfig;++impl SearchQueryConfig for TestSearchConfig {+ const ID_KEY: &'static str = "test_id";+ const INDEX: &'static str = "test_index";+ const USER_ID_KEY: &'static str = "test_user_id";+ const TITLE_KEY: &'static str = "test_title";+}++#[test]+fn test_build_search_request() -> anyhow::Result<()> {+ let bool_query = QueryType::bool_query().build();++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(vec!["test".to_string()])+ .match_type("exact")+ .page_size(20)+ .page(1)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(true)+ .ids(vec!["id1".to_string(), "id2".to_string()])+ .ids_only(true);++ let result = builder.build_search_request(bool_query.clone())?;++ let expected = serde_json::json!({+ "from": 20,+ "size": 20,+ "collapse": {+ "field": "test_id"+ },+ "sort": TestSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ "highlight": TestSearchConfig::default_highlight().to_json(),+ "query": {+ "bool": {}+ }+ });++ assert_eq!(result.to_json(), expected);++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(vec!["test".to_string()])+ .match_type("partial")+ .page_size(20)+ .page(1)+ .user_id("user123")+ .search_on(SearchOn::NameContent)+ .collapse(true)+ .ids(vec!["id1".to_string(), "id2".to_string()]);++ let result = builder.build_search_request(bool_query)?;++ let expected = serde_json::json!({+ "track_total_hits": true,+ "from": 20,+ "size": 20,+ "aggs": {+ "total_uniques": {+ "cardinality": {+ "field": "test_id"+ }+ }+ },+ "collapse": {+ "field": "test_id"+ },+ "sort": [+ {+ "_score": "desc"+ },+ {+ "test_id": "asc"+ }+ ],+ "highlight": {+ "require_field_match": false,+ "fields": {+ "content": {+ "type": "unified",+ "number_of_fragments": 1,+ "pre_tags": ["<macro_em>"],+ "post_tags": ["</macro_em>"],+ },+ "test_title": {+ "type": "unified",+ "number_of_fragments": 1,+ "pre_tags": ["<macro_em>"],+ "post_tags": ["</macro_em>"],+ }+ }+ },+ "query": {+ "function_score": {+ "boost_mode": "multiply",+ "functions": [+ {+ "gauss": {+ "updated_at_seconds": {+ "decay": 0.5,+ "offset": "3d",+ "origin": "now",+ "scale": "21d"+ }+ },+ "weight": 1.3+ }+ ],+ "query": {+ "bool": {}+ },+ "score_mode": "multiply"+ }+ }+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}++#[test]+fn test_build_bool_query() -> anyhow::Result<()> {+ let terms = vec!["test".to_string()];+ let ids = vec!["id1".to_string(), "id2".to_string()];+ let user_id = "user123";+ let page = 1;+ let page_size = 20;++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms.clone())+ .match_type("exact")+ .page_size(page_size)+ .page(page)+ .user_id(user_id)+ .search_on(SearchOn::Content)+ .ids(ids.clone());+ let query = builder.build_bool_query()?;++ let expected = serde_json::json!({+ "bool": {+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "test_id": ["id1", "id2"]+ }+ },+ {+ "term": {+ "test_user_id": "user123"+ }+ }+ ],+ "minimum_should_match": 1,+ }+ });++ assert_eq!(query.build().to_json(), expected);++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms.clone())+ .match_type("partial")+ .page_size(page_size)+ .page(page)+ .user_id(user_id)+ .ids_only(true)+ .search_on(SearchOn::Content)+ .ids(ids.clone());++ let query = builder.build_bool_query()?;++ let expected = serde_json::json!({+ "bool": {+ "must": [+ {+ "match_phrase_prefix": {+ "content": {+ "query": "test",+ }+ }+ }+ ],+ "should": [+ {+ "terms": {+ "test_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"+ }+ }+ }+ ]+ }+ }+ ],+ "should": [+ {+ "terms": {+ "test_id": ["id1", "id2"]+ }+ },+ ],+ "minimum_should_match": 1,+ }+ });++ assert_eq!(query.build().to_json(), expected);++ Ok(())+}++#[test]+fn test_build_must_term_query() -> anyhow::Result<()> {+ let terms = vec!["test".to_string()];++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms.clone())+ .match_type("exact")+ .search_on(SearchOn::Content);++ let terms_must_vec = builder.build_must_term_query()?;++ let expected = serde_json::json!({+ "match_phrase": {+ "content": "test"+ }+ });++ assert_eq!(terms_must_vec.len(), 1);+ assert_eq!(terms_must_vec[0].to_json(), expected);++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms.clone())+ .match_type("exact")+ .search_on(SearchOn::Name);++ let terms_must_vec = builder.build_must_term_query()?;++ let expected = serde_json::json!({+ "match_phrase": {+ "test_title": "test"+ }+ });++ assert_eq!(terms_must_vec.len(), 1);+ assert_eq!(terms_must_vec[0].to_json(), expected);++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms.clone())+ .match_type("partial")+ .search_on(SearchOn::Content);++ let terms_must_vec = builder.build_must_term_query()?;++ let expected = serde_json::json!({+ "match_phrase_prefix": {+ "content": {+ "query": "test",+ }+ }+ });++ 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(())+}++#[test]+fn test_build_must_term_query_multiple_terms() -> anyhow::Result<()> {+ let terms = vec!["test1".to_string(), "test2".to_string()];++ let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms.clone())+ .match_type("exact")+ .search_on(SearchOn::Content);++ let terms_must_vec = builder.build_must_term_query()?;++ let expected = serde_json::json!({+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase": {+ "content": "test1"+ }+ },+ {+ "match_phrase": {+ "content": "test2"+ }+ }+ ]+ }+ });++ 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(())+}++#[test]+fn test_build_must_term_query_term_with_short_last_word() -> anyhow::Result<()> {+ let terms = vec!["test Ab".to_string()];+ let builder = SearchQueryBuilder::<TestSearchConfig>::new(terms)+ .match_type("partial")+ .search_on(SearchOn::Content);++ let terms_must_vec = builder.build_must_term_query()?;++ let expected = serde_json::json!({+ "bool": {+ "must": [+ {+ "match_phrase_prefix": {+ "content": {+ "query": "test",+ }+ }+ },+ {+ "wildcard": {+ "content": {+ "case_insensitive": true,+ "value": "*ab*",+ }+ }+ }+ ]+ }+ });++ assert_eq!(terms_must_vec.len(), 1);+ assert_eq!(terms_must_vec[0].to_json(), expected);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rsindex 2fecf04088..6757bd9914 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs@@ -3,12 +3,15 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::DefaultSearchResponse,+ model::{DefaultSearchResponse, parse_highlight_hit},+ query::Keys,},};use crate::SearchOn;-use opensearch_query_builder::{BoolQueryBuilder, QueryType};+use opensearch_query_builder::{+ FieldSort, QueryType, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+};use serde_json::Value;#[derive(Debug, serde::Serialize, serde::Deserialize)]@@ -50,24 +53,12 @@ impl SearchQueryConfig for ChannelMessageSearchConfig {const USER_ID_KEY: &'static str = "sender_id";const TITLE_KEY: &'static str = "channel_name";- fn default_sort() -> Value {- serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- {- Self::ID_KEY: {- "order": "asc"- }- },- {- "message_id": {- "order": "asc"- }- },- ])+ fn default_sort_types() -> Vec<SortType> {+ vec![+ SortType::Field(FieldSort::new("updated_at_seconds", SortOrder::Desc)),+ SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),+ SortType::Field(FieldSort::new("message_id", SortOrder::Asc)),+ ]}}@@ -89,8 +80,8 @@ impl ChannelMessageQueryBuilder {}}- pub fn org_id(mut self, org_id: i64) -> Self {- self.org_id = Some(org_id);+ pub fn org_id(mut self, org_id: Option<i64>) -> Self {+ self.org_id = org_id;self}@@ -118,54 +109,52 @@ impl ChannelMessageQueryBuilder {// Copy function signature from SearchQueryBuilderdelegate_methods! {fn match_type(match_type: &str) -> Self;- fn page(page: i64) -> Self;- fn page_size(page_size: i64) -> Self;+ fn page(page: u32) -> Self;+ fn page_size(page_size: u32) -> Self;fn user_id(user_id: &str) -> Self;fn search_on(search_on: SearchOn) -> Self;fn ids_only(ids_only: bool) -> Self;fn collapse(collapse: bool) -> Self;}- fn query_builder(- self,- ) -> Result<(- SearchQueryBuilder<ChannelMessageSearchConfig>,- BoolQueryBuilder,- )> {- let mut query_object = self.inner.query_builder()?;+ fn build_search_request(self) -> Result<SearchRequest> {+ // Build the main bool query containing all terms and any other filters+ let mut bool_query = self.inner.build_bool_query()?;++ // CUSTOM ATTRIBUTES SECTION// Add org_id to must clause if providedif let Some(org_id) = self.org_id {- query_object = query_object.must(QueryType::term("org_id", org_id));+ bool_query.must(QueryType::term("org_id", org_id));}// Add thread_ids to must clause if providedif !self.thread_ids.is_empty() {- query_object = query_object.must(QueryType::terms("thread_id", self.thread_ids));+ bool_query.must(QueryType::terms("thread_id", self.thread_ids));}// Add mentions to must clause if providedif !self.mentions.is_empty() {- query_object = query_object.must(QueryType::terms("mentions", self.mentions));+ bool_query.must(QueryType::terms("mentions", self.mentions));}if !self.channel_ids.is_empty() {- query_object = query_object.must(QueryType::terms("channel_id", self.channel_ids));+ bool_query.must(QueryType::terms("channel_id", self.channel_ids));}// Add sender_ids to must clause if providedif !self.sender_ids.is_empty() {- query_object = query_object.must(QueryType::terms("sender_id", self.sender_ids));+ bool_query.must(QueryType::terms("sender_id", self.sender_ids));}- Ok((self.inner, query_object))- }+ // END CUSTOM ATTRIBUTES SECTION- pub fn build(self) -> Result<Value> {- let (builder, query_object) = self.query_builder()?;- let base_query = builder.build_with_query(query_object.build())?;+ // Build the search request with the bool query+ // This will automatically wrap the bool query in a function score if+ // SearchOn::NameContent is used+ let search_request = self.inner.build_search_request(bool_query.build())?;- Ok(base_query)+ Ok(search_request)}}@@ -174,8 +163,8 @@ pub struct ChannelMessageSearchArgs {pub terms: Vec<String>,pub user_id: String,pub channel_ids: Vec<String>,- pub page: i64,- pub page_size: i64,+ pub page: u32,+ pub page_size: u32,pub match_type: String,pub org_id: Option<i64>,pub thread_ids: Vec<String>,@@ -188,7 +177,7 @@ pub struct ChannelMessageSearchArgs {impl ChannelMessageSearchArgs {pub fn build(self) -> Result<Value> {- let mut builder = ChannelMessageQueryBuilder::new(self.terms)+ Ok(ChannelMessageQueryBuilder::new(self.terms).match_type(&self.match_type).page_size(self.page_size).page(self.page)@@ -199,14 +188,10 @@ impl ChannelMessageSearchArgs {.search_on(self.search_on).collapse(self.collapse).ids_only(self.ids_only)- .sender_ids(self.sender_ids);-- // Only add org_id if there is a value provided- if let Some(org_id) = self.org_id {- builder = builder.org_id(org_id);- }-- builder.build()+ .sender_ids(self.sender_ids)+ .org_id(self.org_id)+ .build_search_request()?+ .to_json())}}@@ -214,6 +199,7 @@ pub(crate) async fn search_channel_messages(client: &opensearch::OpenSearch,args: ChannelMessageSearchArgs,) -> Result<Vec<ChannelMessageSearchResponse>> {+ let search_on = args.search_on;let query_body = args.build()?;let response = client@@ -247,351 +233,19 @@ pub(crate) async fn search_channel_messages(mentions: hit._source.mentions,created_at: hit._source.created_at_seconds,updated_at: hit._source.updated_at_seconds,- content: hit.highlight.map(|h| h.content),+ content: hit.highlight.map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ChannelMessageSearchConfig::TITLE_KEY,+ content_key: ChannelMessageSearchConfig::CONTENT_KEY,+ },+ search_on,+ )+ }),}).collect())}#[cfg(test)]-mod tests {- use super::*;- #[test]- fn test_with_additional_fields() {- let query_key = "match_phrase";- let channel_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let thread_ids = vec!["T1".to_string(), "T2".to_string()];- let mentions = vec!["M1".to_string(), "M2".to_string()];- let org_id = 1;- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "sender_id": user_id- }- },- {- "terms": {- "channel_id": channel_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- {- "term": {- "org_id": org_id- }- },- {- "terms": {- "thread_id": thread_ids- }- },- {- "terms": {- "mentions": mentions- }- },- {- "terms": {- "channel_id": channel_ids- }- }- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "channel_id": {- "order": "asc"- }- },- {- "message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = ChannelMessageQueryBuilder::new(vec![query.to_string()])- .mentions(mentions)- .thread_ids(thread_ids)- .org_id(org_id)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(channel_ids)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_sanity() {- let query_key = "match_phrase";- let channel_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "sender_id": user_id- }- },- {- "terms": {- "channel_id": channel_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- {- "terms": {- "channel_id": channel_ids- }- }- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "channel_id": {- "order": "asc"- }- },- {- "message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = ChannelMessageQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(channel_ids)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_ids_only() {- let query_key = "match_phrase";- let channel_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "terms": {- "channel_id": channel_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- {- "terms": {- "channel_id": channel_ids- }- }- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "channel_id": {- "order": "asc"- }- },- {- "message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = ChannelMessageQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(channel_ids)- .ids_only(true)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_sender_ids() {- let channel_ids = vec!["CH1".to_string(), "CH2".to_string()];- let user_id = "user123";- let terms = vec!["search".to_string()];- let sender_ids: Vec<String> = vec!["paul", "ringo", "john", "george"]- .into_iter()- .map(String::from)- .collect();-- let (_, builder) = ChannelMessageQueryBuilder::new(terms)- .match_type("exact")- .page(0)- .page_size(10)- .user_id(user_id)- .ids(channel_ids.clone())- .sender_ids(sender_ids.clone())- .query_builder()- .unwrap();-- let must = if let QueryType::Bool(bool) = builder.build() {- bool.must- } else {- panic!("Could not extract MUST field from bool because type was not a bool");- };-- // Check that sender_ids are in the must field as a terms query- let sender_ids_constraint_found = must.iter().any(|item| {- if let QueryType::Terms(terms_query) = item {- // Check if this is a terms query for "sender_id" field with all expected values- terms_query.field == "sender_id"- && terms_query.values.len() == sender_ids.len()- && sender_ids- .iter()- .all(|id| terms_query.values.iter().any(|v| v.as_str() == Some(id)))- } else {- false- }- });-- assert!(- sender_ids_constraint_found,- "sender_ids should be present in must clause as terms query for sender_id field"- );-- // Also verify that we have the expected number of must clauses- // Should include: search terms, channel_id (from channel_search=true), and sender_id- assert!(- must.len() >= 3,- "Must clause should contain at least 3 items: search terms, channel_id, and sender_id"- );- }-}+mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs b/rust/cloud-storage/opensearch_client/src/search/channels/test.rsnew file mode 100644index 0000000000..b2ac6c229d--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/channels/test.rs@@ -0,0 +1,83 @@+use super::*;+use opensearch_query_builder::ToOpenSearchJson;++#[test]+fn test_build_search_request() -> anyhow::Result<()> {+ let builder = ChannelMessageQueryBuilder::new(vec!["test".to_string()])+ .match_type("exact")+ .page_size(20)+ .page(1)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(true)+ .ids(vec!["id1".to_string(), "id2".to_string()])+ .org_id(Some(123))+ .thread_ids(vec!["thread1".to_string(), "thread2".to_string()])+ .mentions(vec!["mention1".to_string(), "mention2".to_string()])+ .sender_ids(vec!["sender1".to_string(), "sender2".to_string()]);++ let result = builder.build_search_request()?;++ let expected = serde_json::json!({+ "from": 20,+ "size": 20,+ "collapse": {+ "field": "channel_id"+ },+ "sort": ChannelMessageSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ "highlight": ChannelMessageSearchConfig::default_highlight().to_json(),+ "query": {+ "bool": {+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "org_id": 123+ }+ },+ {+ "terms": {+ "thread_id": ["thread1", "thread2"]+ }+ },+ {+ "terms": {+ "mentions": ["mention1", "mention2"]+ }+ },+ {+ "terms": {+ "channel_id": ["id1", "id2"]+ }+ },+ {+ "terms": {+ "sender_id": ["sender1", "sender2"]+ },+ },+ ],+ "should": [+ {+ "terms": {+ "channel_id": ["id1", "id2"]+ }+ },+ {+ "term": {+ "sender_id": "user123"+ }+ }+ ],+ "minimum_should_match": 1,+ }+ }+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rsindex c837cef93a..4b1d497506 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs@@ -3,13 +3,14 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::DefaultSearchResponse,+ model::{DefaultSearchResponse, parse_highlight_hit},+ query::Keys,utils::should_wildcard_field_query_builder,},};use crate::SearchOn;-use opensearch_query_builder::BoolQueryBuilder;+use opensearch_query_builder::{FieldSort, SearchRequest, SortOrder, SortType, ToOpenSearchJson};use serde_json::Value;#[derive(Debug, serde::Serialize, serde::Deserialize)]@@ -42,24 +43,12 @@ impl SearchQueryConfig for ChatSearchConfig {const USER_ID_KEY: &'static str = "user_id";const TITLE_KEY: &'static str = "title";- fn default_sort() -> Value {- serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- {- Self::ID_KEY: {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- },- ])+ fn default_sort_types() -> Vec<SortType> {+ vec![+ SortType::Field(FieldSort::new("updated_at_seconds", SortOrder::Desc)),+ SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),+ SortType::Field(FieldSort::new("chat_message_id", SortOrder::Asc)),+ ]}}@@ -80,8 +69,8 @@ impl ChatQueryBuilder {// Copy function signature from SearchQueryBuilderdelegate_methods! {fn match_type(match_type: &str) -> Self;- fn page(page: i64) -> Self;- fn page_size(page_size: i64) -> Self;+ fn page(page: u32) -> Self;+ fn page_size(page_size: u32) -> Self;fn user_id(user_id: &str) -> Self;fn search_on(search_on: SearchOn) -> Self;fn collapse(collapse: bool) -> Self;@@ -94,19 +83,26 @@ impl ChatQueryBuilder {self}- fn query_builder(self) -> Result<(SearchQueryBuilder<ChatSearchConfig>, BoolQueryBuilder)> {- let mut query_object = self.inner.query_builder()?;+ fn build_search_request(self) -> Result<SearchRequest> {+ // Build the main bool query containing all terms and any other filters+ let mut bool_query = self.inner.build_bool_query()?;++ // CUSTOM ATTRIBUTES SECTION++ // If role is provided, add them to the must queryif !self.role.is_empty() {let should_query = should_wildcard_field_query_builder("role", &self.role);- query_object = query_object.must(should_query);+ bool_query.must(should_query);}- Ok((self.inner, query_object))- }- pub fn build(self) -> Result<Value> {- let (builder, query_object) = self.query_builder()?;- let base_query = builder.build_with_query(query_object.build())?;- Ok(base_query)+ // END CUSTOM ATTRIBUTES SECTION++ // Build the search request with the bool query+ // This will automatically wrap the bool query in a function score if+ // SearchOn::NameContent is used+ let search_request = self.inner.build_search_request(bool_query.build())?;++ Ok(search_request)}}@@ -115,8 +111,8 @@ pub struct ChatSearchArgs {pub terms: Vec<String>,pub user_id: String,pub chat_ids: Vec<String>,- pub page: i64,- pub page_size: i64,+ pub page: u32,+ pub page_size: u32,pub match_type: String,pub role: Vec<String>,pub search_on: SearchOn,@@ -126,7 +122,7 @@ pub struct ChatSearchArgs {impl ChatSearchArgs {pub fn build(self) -> Result<Value> {- ChatQueryBuilder::new(self.terms)+ Ok(ChatQueryBuilder::new(self.terms).match_type(&self.match_type).page_size(self.page_size).page(self.page)@@ -136,7 +132,8 @@ impl ChatSearchArgs {.search_on(self.search_on).collapse(self.collapse).ids_only(self.ids_only)- .build()+ .build_search_request()?+ .to_json())}}@@ -144,6 +141,7 @@ pub(crate) async fn search_chats(client: &opensearch::OpenSearch,args: ChatSearchArgs,) -> Result<Vec<ChatSearchResponse>> {+ let search_on = args.search_on;let query_body = args.build()?;let response = client@@ -172,671 +170,20 @@ pub(crate) async fn search_chats(user_id: hit._source.user_id,role: hit._source.role,title: hit._source.title,- content: hit.highlight.map(|h| h.content),+ content: hit.highlight.map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ChatSearchConfig::TITLE_KEY,+ content_key: ChatSearchConfig::CONTENT_KEY,+ },+ search_on,+ )+ }),updated_at: hit._source.updated_at_seconds,}).collect())}#[cfg(test)]-mod tests {- use super::*;- #[test]- fn test_sanity() {- let query_key = "match_phrase";- let chat_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "chat_id": chat_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "chat_id": {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = ChatQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(chat_ids)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_build_with_single_role() {- let query = "test";- let user_id = "user1";- let role = vec!["user".to_string()];- let page_size = 10;- let page = 0;-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "chat_id": []- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- {- "bool": {- "should": [- {- "wildcard": {- "role": {- "value": "*user*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1- }- }- ],- }- },- "from": 0,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "chat_id": {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = ChatQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .role(role)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_build_with_multiple_roles() {- let query = "test";- let user_id = "user1";- let roles = vec!["user".to_string(), "assistant".to_string()];- let page_size = 10;- let page = 0;-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "chat_id": []- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- {- "bool": {- "should": [- {- "wildcard": {- "role": {- "value": "*user*",- "case_insensitive": true- }- }- },- {- "wildcard": {- "role": {- "value": "*assistant*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1- }- }- ],- }- },- "from": 0,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "chat_id": {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = ChatQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .role(roles)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_build_with_role_and_chat_ids() {- let query = "test";- let user_id = "user1";- let chat_ids = vec!["chat1".to_string(), "chat2".to_string()];- let roles = vec!["user".to_string()];- let page_size = 5;- let page = 1;- let from = page * page_size;-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "chat_id": chat_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- {- "bool": {- "should": [- {- "wildcard": {- "role": {- "value": "*user*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1- }- }- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "chat_id": {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = ChatQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(chat_ids)- .role(roles)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_build_with_empty_role_filter() {- let query = "test";- let user_id = "user1";- let empty_roles = vec![];- let page_size = 10;- let page = 0;-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "chat_id": []- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "content": query- }- },- ],- "minimum_should_match": 1- }- }- ],- }- },- "from": 0,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "chat_id": {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = ChatQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .role(empty_roles)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_ids_only() {- let query_key = "match_phrase";- let chat_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "terms": {- "chat_id": chat_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- },- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "chat_id": {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = ChatQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(chat_ids)- .ids_only(true)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_build_with_role_and_search_on_name() {- let query = "test";- let user_id = "user1";- let roles = vec!["user".to_string()];- let page_size = 10;- let page = 0;-- let reference = serde_json::json!({- "collapse": {- "field": "chat_id"- },- "from": 0,- "highlight": {- "fields": {- "content": {- "number_of_fragments": 500,- "post_tags": ["</macro_em>"],- "pre_tags": ["<macro_em>"],- "require_field_match": true,- "type": "unified"- }- }- },- "query": {- "bool": {- "minimum_should_match": 1,- "must": [- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "match_phrase": {- "title": query- }- }- ]- }- },- {- "bool": {- "minimum_should_match": 1,- "should": [- {- "wildcard": {- "role": {- "case_insensitive": true,- "value": "*user*"- }- }- }- ]- }- }- ],- "should": [- {- "term": {- "user_id": "user1"- }- },- {- "terms": {- "chat_id": []- }- }- ]- }- },- "size": 10,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "chat_id": {- "order": "asc"- }- },- {- "chat_message_id": {- "order": "asc"- }- }- ]- });- let generated = ChatQueryBuilder::new(vec![query.to_string()])- .page_size(page_size)- .page(page)- .user_id(user_id)- .role(roles)- .search_on(SearchOn::Name)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-}+mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs b/rust/cloud-storage/opensearch_client/src/search/chats/test.rsnew file mode 100644index 0000000000..6ce7aa29a5--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/chats/test.rs@@ -0,0 +1,78 @@+use super::*;+use opensearch_query_builder::ToOpenSearchJson;++#[test]+fn test_build_search_request() -> anyhow::Result<()> {+ let builder = ChatQueryBuilder::new(vec!["test".to_string()])+ .match_type("exact")+ .page_size(20)+ .page(1)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(true)+ .ids(vec!["chat1".to_string(), "chat2".to_string()])+ .role(vec!["user".to_string(), "assistant".to_string()]);++ let result = builder.build_search_request()?;++ let expected = serde_json::json!({+ "from": 20,+ "size": 20,+ "collapse": {+ "field": "chat_id"+ },+ "sort": ChatSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ "highlight": ChatSearchConfig::default_highlight().to_json(),+ "query": {+ "bool": {+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*user*"+ }+ }+ },+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*assistant*"+ }+ }+ }+ ]+ }+ }+ ],+ "should": [+ {+ "terms": {+ "chat_id": ["chat1", "chat2"]+ }+ },+ {+ "term": {+ "user_id": "user123"+ }+ }+ ],+ "minimum_should_match": 1,+ }+ }+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex f3b89c358d..666d521ac9 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -3,12 +3,15 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::{DefaultHit, DefaultSearchResponse},+ model::{DefaultSearchResponse, parse_highlight_hit},+ query::Keys,},};use crate::SearchOn;-use opensearch_query_builder::{BoolQueryBuilder, QueryType};+use opensearch_query_builder::{+ FieldSort, QueryType, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+};use serde_json::Value;#[derive(Clone)]@@ -20,24 +23,12 @@ impl SearchQueryConfig for DocumentSearchConfig {const USER_ID_KEY: &'static str = "owner_id";const TITLE_KEY: &'static str = "document_name";- fn default_sort() -> Value {- serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- {- Self::ID_KEY: {- "order": "asc"- }- },- {- "node_id": {- "order": "asc"- }- }- ])+ fn default_sort_types() -> Vec<SortType> {+ vec![+ SortType::Field(FieldSort::new("updated_at_seconds", SortOrder::Desc)),+ SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),+ SortType::Field(FieldSort::new("node_id", SortOrder::Asc)),+ ]}}@@ -58,8 +49,8 @@ impl DocumentQueryBuilder {// Copy function signature from SearchQueryBuilderdelegate_methods! {fn match_type(match_type: &str) -> Self;- fn page(page: i64) -> Self;- fn page_size(page_size: i64) -> Self;+ fn page(page: u32) -> Self;+ fn page_size(page_size: u32) -> Self;fn user_id(user_id: &str) -> Self;fn search_on(search_on: SearchOn) -> Self;fn collapse(collapse: bool) -> Self;@@ -72,20 +63,25 @@ impl DocumentQueryBuilder {self}- fn query_builder(self) -> Result<(SearchQueryBuilder<DocumentSearchConfig>, BoolQueryBuilder)> {- let mut query_object = self.inner.query_builder()?;- // Add in file types to must query+ fn build_search_request(self) -> Result<SearchRequest> {+ // Build the main bool query containing all terms and any other filters+ let mut bool_query = self.inner.build_bool_query()?;++ // CUSTOM ATTRIBUTES SECTION++ // If file types are provided, add them to the must queryif !self.file_types.is_empty() {- query_object = query_object.must(QueryType::terms("file_type", self.file_types));+ bool_query.must(QueryType::terms("file_type", self.file_types));}- Ok((self.inner, query_object))- }- pub fn build(self) -> Result<Value> {- let (builder, query_object) = self.query_builder()?;- let base_query = builder.build_with_query(query_object.build())?;+ // END CUSTOM ATTRIBUTES SECTION++ // Build the search request with the bool query+ // This will automatically wrap the bool query in a function score if+ // SearchOn::NameContent is used+ let search_request = self.inner.build_search_request(bool_query.build())?;- Ok(base_query)+ Ok(search_request)}}@@ -119,8 +115,8 @@ pub struct DocumentSearchArgs {pub user_id: String,pub document_ids: Vec<String>,pub file_types: Vec<String>,- pub page: i64,- pub page_size: i64,+ pub page: u32,+ pub page_size: u32,pub match_type: String,pub search_on: SearchOn,pub collapse: bool,@@ -129,7 +125,7 @@ pub struct DocumentSearchArgs {impl DocumentSearchArgs {pub fn build(self) -> Result<Value> {- DocumentQueryBuilder::new(self.terms)+ Ok(DocumentQueryBuilder::new(self.terms).match_type(&self.match_type).page_size(self.page_size).page(self.page)@@ -139,22 +135,8 @@ impl DocumentSearchArgs {.search_on(self.search_on).collapse(self.collapse).ids_only(self.ids_only)- .build()- }-}--impl From<DefaultHit<DocumentIndex>> for DocumentSearchResponse {- fn from(hit: DefaultHit<DocumentIndex>) -> Self {- Self {- document_id: hit._source.document_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,- content: hit.highlight.map(|h| h.content),- raw_content: hit._source.raw_content,- }+ .build_search_request()?+ .to_json())}}@@ -162,8 +144,11 @@ pub(crate) async fn search_documents(client: &opensearch::OpenSearch,args: DocumentSearchArgs,) -> Result<Vec<DocumentSearchResponse>> {+ let search_on = args.search_on;let query_body = args.build()?;+ tracing::trace!("query: {}", query_body);+let response = client.search(opensearch::SearchParts::Index(&[DOCUMENTS_INDEX])).body(query_body)@@ -184,356 +169,27 @@ pub(crate) async fn search_documents(.hits.hits.into_iter()- .map(DocumentSearchResponse::from)+ .map(|hit| DocumentSearchResponse {+ document_id: hit._source.document_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,+ content: hit.highlight.map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: DocumentSearchConfig::TITLE_KEY,+ content_key: DocumentSearchConfig::CONTENT_KEY,+ },+ search_on,+ )+ }),+ }).collect())}#[cfg(test)]-mod tests {- use super::*;- #[test]- fn test_file_types() {- let query_key = "match_phrase";- let file_types = vec!["pdf".to_string(), "docx".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let terms = vec!["test".to_string()];- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "owner_id": user_id- }- },- {- "terms": {- "document_id": Vec::<String>::new()- }- },- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": terms[0]- }- },- ],- "minimum_should_match": 1- }- },- {- "terms": {- "file_type": file_types- }- }- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "document_id": {- "order": "asc"- }- },- {- "node_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = DocumentQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .file_types(file_types)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_sanity() {- let query_key = "match_phrase";- let document_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let terms = vec!["test".to_string()];- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "owner_id": user_id- }- },- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": terms[0]- }- },- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "document_id": {- "order": "asc"- }- },- {- "node_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = DocumentQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(document_ids)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_ids_only() {- let query_key = "match_phrase";- let document_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let terms = vec!["test".to_string()];- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": terms[0]- }- },- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "document_id": {- "order": "asc"- }- },- {- "node_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- });-- let generated = DocumentQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(document_ids)- .ids_only(true)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_name_search() {- let query_key = "match_phrase";- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let terms = vec!["test".to_string()];- let document_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let reference = serde_json::json!({- "collapse": {- "field": "document_id"- },- "from": from,- "highlight": {- "fields": {- "content": {- "type": "unified", // The way the highlight is done- "number_of_fragments": 500, // Breaks up the "content" field into said- "pre_tags": ["<macro_em>"], // HTML tag before highlight- "post_tags": ["</macro_em>"], // HTML tag after highlight- "require_field_match": true, // Default is true, but good to be explicit- }- }- },- "query": {-- "bool": {- "should": [- {- "term": {- "owner_id": user_id- }- },- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "document_name": terms[0]- }- },- ],- "minimum_should_match": 1- }- },- ],- }- },- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "document_id": {- "order": "asc"- }- },- {- "node_id": {- "order": "asc"- }- },- ],- });-- let generated = DocumentQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(document_ids)- .search_on(SearchOn::Name)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-}+mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rsnew file mode 100644index 0000000000..bfbb4a3f4a--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs@@ -0,0 +1,60 @@+use super::*;+use opensearch_query_builder::ToOpenSearchJson;++#[test]+fn test_build_search_request() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["test".to_string()])+ .match_type("exact")+ .page_size(20)+ .page(1)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(true)+ .ids(vec!["doc1".to_string(), "doc2".to_string()])+ .file_types(vec!["pdf".to_string(), "docx".to_string()]);++ let result = builder.build_search_request()?;++ let expected = serde_json::json!({+ "from": 20,+ "size": 20,+ "collapse": {+ "field": "document_id"+ },+ "sort": DocumentSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ "highlight": DocumentSearchConfig::default_highlight().to_json(),+ "query": {+ "bool": {+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "terms": {+ "file_type": ["pdf", "docx"]+ }+ }+ ],+ "should": [+ {+ "terms": {+ "document_id": ["doc1", "doc2"]+ }+ },+ {+ "term": {+ "owner_id": "user123"+ }+ }+ ],+ "minimum_should_match": 1,+ }+ }+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 061222aa9f..347b7360d7 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -3,12 +3,16 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},+ model::parse_highlight_hit,+ query::Keys,utils::should_wildcard_field_query_builder,},};use crate::SearchOn;-use opensearch_query_builder::{BoolQueryBuilder, QueryType};+use opensearch_query_builder::{+ FieldSort, QueryType, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+};use crate::search::model::DefaultSearchResponse;use serde_json::Value;@@ -21,24 +25,12 @@ impl SearchQueryConfig for EmailSearchConfig {const USER_ID_KEY: &'static str = "user_id";const TITLE_KEY: &'static str = "subject";- fn default_sort() -> Value {- serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- {- Self::ID_KEY: {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- }- ])+ fn default_sort_types() -> Vec<SortType> {+ vec![+ SortType::Field(FieldSort::new("updated_at_seconds", SortOrder::Desc)),+ SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),+ SortType::Field(FieldSort::new("thread_id", SortOrder::Asc)),+ ]}}@@ -74,8 +66,8 @@ impl EmailQueryBuilder {// Copy function signature from SearchQueryBuilderdelegate_methods! {fn match_type(match_type: &str) -> Self;- fn page(page: i64) -> Self;- fn page_size(page_size: i64) -> Self;+ fn page(page: u32) -> Self;+ fn page_size(page_size: u32) -> Self;fn user_id(user_id: &str) -> Self;fn search_on(search_on: SearchOn) -> Self;fn collapse(collapse: bool) -> Self;@@ -113,51 +105,54 @@ impl EmailQueryBuilder {self}- fn query_builder(self) -> Result<(SearchQueryBuilder<EmailSearchConfig>, BoolQueryBuilder)> {- let mut query_object = self.inner.query_builder()?;+ fn build_search_request(self) -> Result<SearchRequest> {+ // Build the main bool query containing all terms and any other filters+ let mut bool_query = self.inner.build_bool_query()?;++ // CUSTOM ATTRIBUTES SECTION// If thread_ids are provided, add them to the queryif !self.thread_ids.is_empty() {- query_object = query_object.must(QueryType::terms("thread_id", self.thread_ids));+ bool_query.must(QueryType::terms("thread_id", self.thread_ids));}// If link_ids are provided, add them to the queryif !self.link_ids.is_empty() {- query_object = query_object.must(QueryType::terms("link_id", self.link_ids));+ bool_query.must(QueryType::terms("link_id", self.link_ids));}if !self.sender.is_empty() {// Create new query for senderslet senders_query = should_wildcard_field_query_builder("sender", &self.sender);- query_object = query_object.must(senders_query);+ bool_query.must(senders_query);}if !self.cc.is_empty() {let ccs_query = should_wildcard_field_query_builder("cc", &self.cc);- query_object = query_object.must(ccs_query);+ bool_query.must(ccs_query);}if !self.bcc.is_empty() {// Create new query for bccslet bccs_query = should_wildcard_field_query_builder("bcc", &self.bcc);- query_object = query_object.must(bccs_query);+ bool_query.must(bccs_query);}if !self.recipients.is_empty() {// Create new query for recipientslet recipients_query =should_wildcard_field_query_builder("recipients", &self.recipients);- query_object = query_object.must(recipients_query);+ bool_query.must(recipients_query);}- Ok((self.inner, query_object))- }+ // END CUSTOM ATTRIBUTES SECTION- pub fn build(self) -> Result<Value> {- let (builder, query_object) = self.query_builder()?;- let base_query = builder.build_with_query(query_object.build())?;+ // Build the search request with the bool query+ // This will automatically wrap the bool query in a function score if+ // SearchOn::NameContent is used+ let search_request = self.inner.build_search_request(bool_query.build())?;- Ok(base_query)+ Ok(search_request)}}@@ -218,8 +213,8 @@ pub struct EmailSearchArgs {pub cc: Vec<String>,pub bcc: Vec<String>,pub recipients: Vec<String>,- pub page: i64,- pub page_size: i64,+ pub page: u32,+ pub page_size: u32,pub match_type: String,pub search_on: SearchOn,pub collapse: bool,@@ -228,7 +223,7 @@ pub struct EmailSearchArgs {impl EmailSearchArgs {pub fn build(self) -> Result<Value> {- EmailQueryBuilder::new(self.terms)+ Ok(EmailQueryBuilder::new(self.terms).match_type(&self.match_type).page_size(self.page_size).page(self.page)@@ -243,7 +238,8 @@ impl EmailSearchArgs {.recipients(self.recipients).collapse(self.collapse).ids_only(self.ids_only)- .build()+ .build_search_request()?+ .to_json())}}@@ -251,6 +247,7 @@ pub(crate) async fn search_emails(client: &opensearch::OpenSearch,args: EmailSearchArgs,) -> Result<Vec<EmailSearchResponse>> {+ let search_on = args.search_on;let query_body = args.build()?;let response = client@@ -286,10 +283,16 @@ pub(crate) async fn search_emails(user_id: hit._source.user_id,updated_at: hit._source.updated_at_seconds,sent_at: hit._source.sent_at_seconds,- content: hit- .highlight- .map(|h| h.content)- .or(Some(vec![hit._source.content])),+ content: hit.highlight.map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: EmailSearchConfig::TITLE_KEY,+ content_key: EmailSearchConfig::CONTENT_KEY,+ },+ search_on,+ )+ }),}).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 127288cb55..5ac33f4308 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -1,835 +1,130 @@use super::*;+use opensearch_query_builder::ToOpenSearchJson;#[test]-fn test_email_query_with_thread_ids() {- let query_key = "match_phrase";- let message_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let thread_ids = vec!["thread1".to_string(), "thread2".to_string()];- let link_ids = vec!["link1".to_string(), "link2".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let terms = vec![query.to_string()];-- let reference = serde_json::json!({+fn test_build_search_request() -> anyhow::Result<()> {+ let builder = EmailQueryBuilder::new(vec!["test".to_string()])+ .match_type("exact")+ .page_size(20)+ .page(1)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(true)+ .ids(vec!["msg1".to_string(), "msg2".to_string()])+ .thread_ids(vec!["thread1".to_string(), "thread2".to_string()])+ .link_ids(vec!["link1".to_string(), "link2".to_string()])+ .sender(vec!["[email protected]".to_string()])+ .cc(vec!["[email protected]".to_string()])+ .bcc(vec!["[email protected]".to_string()])+ .recipients(vec!["[email protected]".to_string()]);++ let result = builder.build_search_request()?;++ let expected = serde_json::json!({+ "from": 20,+ "size": 20,+ "collapse": {+ "field": "message_id"+ },+ "sort": EmailSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ "highlight": EmailSearchConfig::default_highlight().to_json(),"query": {"bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "message_id": message_ids- }- },- ],"minimum_should_match": 1,"must": [{- "bool": {- "should": [- {- query_key: {- "content": query- }- }- ],- "minimum_should_match": 1+ "match_phrase": {+ "content": "test"}},{"terms": {- "thread_id": thread_ids+ "thread_id": ["thread1", "thread2"]}},{"terms": {- "link_id": link_ids- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = EmailQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(message_ids)- .thread_ids(thread_ids)- .link_ids(link_ids)- .search_on(SearchOn::Content)- .build()- .unwrap();-- let s1 = serde_json::to_string_pretty(&generated).unwrap();- let s2 = serde_json::to_string_pretty(&reference).unwrap();-- println!("{}", s1);- println!("{}", s2);-- assert_eq!(&generated, &reference);-}--#[test]-fn test_email_query_with_senders() {- let query_key = "match_phrase";- let senders = vec!["sender1".to_string(), "seNdeR2".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "message_id": Vec::<String>::new()- }- },- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- }- ],- "minimum_should_match": 1+ "link_id": ["link1", "link2"]}},{"bool": {+ "minimum_should_match": 1,"should": [{"wildcard": {"sender": {- "value": "*sender1*",- "case_insensitive": true- }- }- },- {- "wildcard": {- "sender": {- "value": "*sender2*",- "case_insensitive": true+ "case_insensitive": true,+ "value": "*[email protected]*"}}}- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = EmailQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .sender(senders)- .search_on(SearchOn::Content)- .build()- .unwrap();-- assert_eq!(&generated, &reference);-}--#[test]-fn test_email_query_with_cc() {- let query_key = "match_phrase";- let cc = vec!["cc1".to_string(), "cC2".to_string()];- let bcc = vec!["bcc1".to_string(), "bCc2".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "message_id": Vec::<String>::new()- }- },- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- }- ],- "minimum_should_match": 1+ ]}},{"bool": {+ "minimum_should_match": 1,"should": [{"wildcard": {"cc": {- "value": "*cc1*",- "case_insensitive": true- }- }- },- {- "wildcard": {- "cc": {- "value": "*cc2*",- "case_insensitive": true+ "case_insensitive": true,+ "value": "*[email protected]*"}}}- ],- "minimum_should_match": 1+ ]}},{"bool": {+ "minimum_should_match": 1,"should": [{"wildcard": {"bcc": {- "value": "*bcc1*",- "case_insensitive": true+ "case_insensitive": true,+ "value": "*[email protected]*"}}- },- {- "wildcard": {- "bcc": {- "value": "*bcc2*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = EmailQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .cc(cc)- .bcc(bcc)- .search_on(SearchOn::Content)- .build()- .unwrap();-- assert_eq!(&generated, &reference);-}--#[test]-fn test_email_query_with_recipients() {- let query_key = "match_phrase";- let recipients = vec!["recipient1".to_string(), "recipient2".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "message_id": Vec::<String>::new()- }- },- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }}- ],- "minimum_should_match": 1+ ]}},{"bool": {+ "minimum_should_match": 1,"should": [{"wildcard": {"recipients": {- "value": "*recipient1*",- "case_insensitive": true+ "case_insensitive": true,+ "value": "*[email protected]*"}}- },- {- "wildcard": {- "recipients": {- "value": "*recipient2*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = EmailQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .recipients(recipients)- .search_on(SearchOn::Content)- .build()- .unwrap();-- assert_eq!(&generated, &reference);-}--#[test]-fn test_ids_only() {- let query_key = "match_phrase";- let message_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let terms = vec![query.to_string()];- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "terms": {- "message_id": message_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }}- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = EmailQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(message_ids)- .ids_only(true)- .search_on(SearchOn::Content)- .build()- .unwrap();-- assert_eq!(&generated, &reference);-}--#[test]-fn test_sanity() {- let query_key = "match_phrase";- let message_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "term": {- "user_id": user_id- }- },- {- "terms": {- "message_id": message_ids+ ]}}],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "content": query- }- }- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = EmailQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(message_ids)- .search_on(SearchOn::Content)- .build()- .unwrap();-- assert_eq!(&generated, &reference);-}-#[test]-fn test_email_name_only_search() {- let query_key = "match_phrase";- let message_ids = vec!["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";-- let reference = serde_json::json!({- "query": {- "bool": {"should": [- {- "term": {- "user_id": user_id- }- },{"terms": {- "message_id": message_ids+ "message_id": ["msg1", "msg2"]}},- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "subject": query- }- }- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "collapse": {- "field": "message_id"- },- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = EmailQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(message_ids)- .search_on(SearchOn::Name)- .build()- .unwrap();-- assert_eq!(&generated, &reference);-}--#[test]-fn test_email_name_only_with_senders() {- let query_key = "match_phrase";- let senders = vec!["sender1".to_string(), "seNdeR2".to_string()];- let user_id = "user";- let page = 1;- let page_size = 2;- let from = page * page_size;- let query = "test";-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [{"term": {- "user_id": user_id- }- },- {- "terms": {- "message_id": Vec::<String>::new()- }- },- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- query_key: {- "subject": query- }- }- ],- "minimum_should_match": 1- }- },- {- "bool": {- "should": [- {- "wildcard": {- "sender": {- "value": "*sender1*",- "case_insensitive": true- }- }- },- {- "wildcard": {- "sender": {- "value": "*sender2*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1+ "user_id": "user123"}- },- ],- }- },- "from": from,- "size": page_size,- "collapse": {- "field": "message_id"- },- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "message_id": {- "order": "asc"- }- },- {- "thread_id": {- "order": "asc"- }- },- ],- "highlight": {- "fields": {- "content": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }+ }+ ]}- },+ }});- let generated = EmailQueryBuilder::new(vec![query.to_string()])- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .sender(senders)- .search_on(SearchOn::Name)- .build()- .unwrap();+ assert_eq!(result.to_json(), expected);- assert_eq!(&generated, &reference);+ Ok(())}diff --git a/rust/cloud-storage/opensearch_client/src/search/model.rs b/rust/cloud-storage/opensearch_client/src/search/model.rsindex a3142eb3c4..46269778d0 100644--- a/rust/cloud-storage/opensearch_client/src/search/model.rs+++ b/rust/cloud-storage/opensearch_client/src/search/model.rs@@ -1,19 +1,63 @@-#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct HighlightContent {- /// Contains an array of highlighted text fragments- pub content: Vec<String>,+use std::{collections::HashMap, fmt::Display};++use crate::{SearchOn, search::query::Keys};++/// macro open/close tags for highlight matches+#[derive(Debug, PartialEq)]+pub enum MacroEm {+ /// Open tag <macro_em>+ Open,+ /// Close tag </macro_em>+ Close,+}++impl Display for MacroEm {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Open => write!(f, "<macro_em>"),+ Self::Close => write!(f, "</macro_em>"),+ }+ }}#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct Hit<T, U> {+pub struct Hit<T> {pub _score: Option<f64>,pub _source: T,/// Highlights may or may not be present since we could match/// purely on the title of the item- pub highlight: Option<U>,+ pub highlight: Option<HashMap<String, Vec<String>>>,}-pub type DefaultHit<T> = Hit<T, HighlightContent>;+pub(crate) fn parse_highlight_hit(+ highlight: HashMap<String, Vec<String>>,+ keys: Keys,+ search_on: SearchOn,+) -> Vec<String> {+ match search_on {+ SearchOn::Name => highlight+ .get(keys.title_key)+ .map(|v| v.to_vec())+ .unwrap_or_default(),+ SearchOn::Content => highlight+ .get(keys.content_key)+ .map(|v| v.to_vec())+ .unwrap_or_default(),+ SearchOn::NameContent => {+ let mut result = Vec::new();++ if let Some(highlight) = highlight.get(keys.title_key) {+ result.extend(highlight.to_vec());+ }++ if let Some(highlight) = highlight.get(keys.content_key) {+ result.extend(highlight.to_vec());+ }++ result+ }+ }+}#[derive(Debug, serde::Serialize, serde::Deserialize)]pub struct Total {@@ -22,10 +66,10 @@ pub struct Total {}#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct Hits<T, U> {+pub struct Hits<T> {pub total: Total,pub max_score: Option<f64>,- pub hits: Vec<Hit<T, U>>,+ pub hits: Vec<Hit<T>>,}#[derive(Debug, serde::Serialize, serde::Deserialize)]@@ -36,11 +80,11 @@ pub struct Shards {pub failed: i32,}-pub type DefaultSearchResponse<T> = SearchResponse<T, HighlightContent>;+pub type DefaultSearchResponse<T> = SearchResponse<T>;#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct SearchResponse<T, U> {- pub hits: Hits<T, U>,+pub struct SearchResponse<T> {+ pub hits: Hits<T>,pub took: i32,pub timed_out: bool,pub _shards: Shards,diff --git a/rust/cloud-storage/opensearch_client/src/search/projects.rs b/rust/cloud-storage/opensearch_client/src/search/projects.rsindex 9930e2166c..9830e5750f 100644--- a/rust/cloud-storage/opensearch_client/src/search/projects.rs+++ b/rust/cloud-storage/opensearch_client/src/search/projects.rs@@ -3,12 +3,15 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryBuilder, SearchQueryConfig},- model::{Hit, SearchResponse},+ model::{MacroEm, SearchResponse, parse_highlight_hit},+ query::Keys,},};use crate::SearchOn;-use opensearch_query_builder::{BoolQueryBuilder, Highlight, HighlightField, ToOpenSearchJson};+use opensearch_query_builder::{+ FieldSort, Highlight, HighlightField, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+};use serde::{Deserialize, Serialize};use serde_json::Value;@@ -21,34 +24,23 @@ impl SearchQueryConfig for ProjectSearchConfig {const USER_ID_KEY: &'static str = "user_id";const TITLE_KEY: &'static str = "project_name";- fn default_sort() -> Value {- serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- {- Self::ID_KEY: {- "order": "asc"- }- }- ])+ fn default_sort_types() -> Vec<SortType> {+ vec![+ SortType::Field(FieldSort::new("updated_at_seconds", SortOrder::Desc)),+ SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),+ ]}// Projects have no "content" to highlight match on, so match on the TITLE_KEY instead- fn default_highlight() -> Value {- Highlight::new()- .field(- Self::TITLE_KEY,- HighlightField::new()- .highlight_type("unified")- .number_of_fragments(500)- .pre_tags(vec!["<macro_em>".to_string()])- .post_tags(vec!["</macro_em>".to_string()])- .require_field_match(true),- )- .to_json()+ fn default_highlight() -> Highlight {+ Highlight::new().require_field_match(true).field(+ Self::TITLE_KEY,+ HighlightField::new()+ .highlight_type("unified")+ .number_of_fragments(1)+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()]),+ )}}@@ -67,8 +59,8 @@ impl ProjectQueryBuilder {// Copy function signature from SearchQueryBuilderdelegate_methods! {fn match_type(match_type: &str) -> Self;- fn page(page: i64) -> Self;- fn page_size(page_size: i64) -> Self;+ fn page(page: u32) -> Self;+ fn page_size(page_size: u32) -> Self;fn user_id(user_id: &str) -> Self;fn search_on(search_on: SearchOn) -> Self;fn collapse(collapse: bool) -> Self;@@ -76,17 +68,16 @@ impl ProjectQueryBuilder {fn ids_only(ids_only: bool) -> Self;}- fn query_builder(self) -> Result<(SearchQueryBuilder<ProjectSearchConfig>, BoolQueryBuilder)> {- let query_object = self.inner.query_builder()?;+ fn build_search_request(self) -> Result<SearchRequest> {+ // Build the main bool query containing all terms and any other filters+ let bool_query = self.inner.build_bool_query()?;- Ok((self.inner, query_object))- }+ // Build the search request with the bool query+ // This will automatically wrap the bool query in a function score if+ // SearchOn::NameContent is used+ let search_request = self.inner.build_search_request(bool_query.build())?;- pub fn build(self) -> Result<Value> {- let (builder, query_object) = self.query_builder()?;- let base_query = builder.build_with_query(query_object.build())?;-- Ok(base_query)+ Ok(search_request)}}@@ -104,8 +95,8 @@ pub struct ProjectIndex {pub struct ProjectSearchArgs {pub terms: Vec<String>,pub user_id: String,- pub page: i64,- pub page_size: i64,+ pub page: u32,+ pub page_size: u32,pub match_type: String,pub project_ids: Vec<String>,pub search_on: SearchOn,@@ -124,7 +115,8 @@ impl ProjectSearchArgs {.collapse(self.collapse).ids(self.project_ids).ids_only(self.ids_only);- builder.build()++ Ok(builder.build_search_request()?.to_json())}}@@ -138,28 +130,11 @@ pub struct ProjectSearchResponse {pub content: Option<Vec<String>>,}-#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct HighlightProject {- pub project_name: Vec<String>,-}--impl From<Hit<ProjectIndex, HighlightProject>> for ProjectSearchResponse {- fn from(hit: Hit<ProjectIndex, HighlightProject>) -> Self {- Self {- project_id: hit._source.project_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,- content: hit.highlight.map(|h| h.project_name),- }- }-}-pub(crate) async fn search_projects(client: &opensearch::OpenSearch,args: ProjectSearchArgs,) -> Result<Vec<ProjectSearchResponse>> {+ let search_on = args.search_on;let query_body = args.build()?;let response = client@@ -179,399 +154,36 @@ pub(crate) async fn search_projects(method: Some("search_projects".to_string()),})?;- let result: SearchResponse<ProjectIndex, HighlightProject> = serde_json::from_value(json_value)- .map_err(|e| OpensearchClientError::DeserializationFailed {+ let result: SearchResponse<ProjectIndex> = serde_json::from_value(json_value).map_err(|e| {+ OpensearchClientError::DeserializationFailed {details: e.to_string(),method: Some("search_projects".to_string()),- })?;+ }+ })?;Ok(result.hits.hits.into_iter()- .map(ProjectSearchResponse::from)+ .map(|hit| ProjectSearchResponse {+ project_id: hit._source.project_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,+ content: hit.highlight.map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ProjectSearchConfig::TITLE_KEY,+ content_key: ProjectSearchConfig::CONTENT_KEY,+ },+ search_on,+ )+ }),+ }).collect())}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_project_query_builder_basic_build() {- let terms = vec!["project".to_string(), "search".to_string()];- let result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .page(0)- .page_size(10)- .match_type("exact")- .build()- .unwrap();-- // Verify structure contains expected keys- assert!(result.get("query").is_some());- assert!(result.get("from").is_some());- assert!(result.get("size").is_some());- assert!(result.get("sort").is_some());- assert!(result.get("highlight").is_some());-- // Verify pagination- assert_eq!(result["from"], serde_json::json!(0));- assert_eq!(result["size"], serde_json::json!(10));-- // Verify default sort for projects- let expected_sort = serde_json::json!([- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "project_id": {- "order": "asc"- }- }- ]);- assert_eq!(result["sort"], expected_sort);-- let expected_highlight = serde_json::json!({- "fields": {- "project_name": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- });- // Verify empty highlight (project-specific)- assert_eq!(result["highlight"], expected_highlight);- }-- #[test]- fn test_project_query_builder_name_search_mode() {- let terms = vec!["project".to_string()];- let result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .search_on(SearchOn::Name)- .build()- .unwrap();-- // In Name search mode, it should search on name/title field- // which creates a different query structure focused on title matching- assert!(result.get("query").is_some());- assert!(result["query"]["bool"].is_object());- }-- #[test]- fn test_project_query_builder_full_mode() {- let terms = vec!["project".to_string()];- let result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .search_on(SearchOn::Content)- .build()- .unwrap();-- // In Content search mode, it should use the regular query builder- assert!(result.get("query").is_some());- assert!(result["query"]["bool"].is_object());- }-- #[test]- fn test_project_query_builder_with_project_ids() {- let terms = vec!["project".to_string()];- let project_ids = vec!["proj1".to_string(), "proj2".to_string()];-- let result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .search_on(SearchOn::Content)- .ids(project_ids.clone())- .build()- .unwrap();-- // The ids() method delegates to inner builder which adds to "should" clause, not "must"- let should_clause = &result["query"]["bool"]["should"];- assert!(should_clause.is_array());-- let should_array = should_clause.as_array().unwrap();-- // Look for project_id terms in should clause (where they actually end up)- let project_terms_found = should_array.iter().any(|item| {- item.get("terms")- .and_then(|t| t.get("project_id"))- .and_then(|v| v.as_array())- .map(|arr| arr.len() == 2)- .unwrap_or(false)- });- assert!(project_terms_found);- }-- #[test]- fn test_project_query_builder_combined_filters() {- let terms = vec!["project".to_string()];- let project_ids = vec!["proj1".to_string(), "proj2".to_string()];-- let result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .search_on(SearchOn::Content)- .ids(project_ids.clone())- .page(1)- .page_size(20)- .build()- .unwrap();-- // Verify pagination- assert_eq!(result["from"], serde_json::json!(20)); // page 1 * page_size 20- assert_eq!(result["size"], serde_json::json!(20));-- // Verify both should and must clauses exist- assert!(result["query"]["bool"]["should"].is_array());- assert!(result["query"]["bool"]["must"].is_array());-- let should_array = result["query"]["bool"]["should"].as_array().unwrap();-- // Should also contain project_id terms from ids() - they both go to should clause- let project_terms_found = should_array.iter().any(|item| {- item.get("terms")- .and_then(|t| t.get("project_id"))- .is_some()- });- assert!(project_terms_found);- }-- #[test]- fn test_project_query_builder_empty_filters() {- let terms = vec!["project".to_string()];-- let result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .search_on(SearchOn::Content)- .ids(vec![])- .build()- .unwrap();-- // With empty filters, no additional terms should be added- // The base query structure should still be valid- assert!(result.get("query").is_some());- assert!(result["query"]["bool"].is_object());- }-- #[test]- fn test_project_query_builder_different_match_types() {- let terms = vec!["project".to_string()];-- let exact_result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .match_type("exact")- .search_on(SearchOn::Content)- .build()- .unwrap();-- let partial_result = ProjectQueryBuilder::new(terms.clone())- .user_id("user123")- .match_type("partial")- .search_on(SearchOn::Content)- .build()- .unwrap();-- // Both should build successfully with different internal query structures- assert!(exact_result.get("query").is_some());- assert!(partial_result.get("query").is_some());-- // They should have the same overall structure but different query internals- assert_eq!(exact_result.get("sort"), partial_result.get("sort"));- assert_eq!(- exact_result.get("highlight"),- partial_result.get("highlight")- );- }-- #[test]- fn test_ids_only() {- let terms = vec!["project".to_string()];- let project_ids = vec!["proj1".to_string(), "proj2".to_string()];- let user_id = "user123";- let page = 1;- let page_size = 10;- let from = page * page_size;-- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "terms": {- "project_id": project_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "project_name": terms[0]- }- },- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "collapse": {- "field": "project_id"- },- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "project_id": {- "order": "asc"- }- }- ],- "highlight": {- "fields": {- "project_name": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = ProjectQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(project_ids)- .ids_only(true)- .search_on(SearchOn::Name)- .build()- .unwrap();-- assert_eq!(&generated, &reference);- }-- #[test]- fn test_project_search_args_build() {- let args = ProjectSearchArgs {- terms: vec!["test".to_string()],- user_id: "user123".to_string(),- page: 1,- page_size: 15,- match_type: "partial".to_string(), // Use valid match type- project_ids: vec!["proj1".to_string()],- search_on: SearchOn::Content,- collapse: false,- ids_only: false,- };-- let result = args.build().unwrap();-- // Verify all parameters are correctly applied- assert_eq!(result["from"], serde_json::json!(15)); // page 1 * page_size 15- assert_eq!(result["size"], serde_json::json!(15));-- // Verify query structure exists- assert!(result["query"]["bool"].is_object());-- // In Content search mode with filters, should have both should and must clauses- assert!(result["query"]["bool"]["should"].is_array());- assert!(result["query"]["bool"]["must"].is_array());- }-}--#[test]-fn test_project_content_search_syntactically_invalid() {- let terms = vec!["project".to_string()];- let project_ids = vec!["proj1".to_string(), "proj2".to_string()];- let user_id = "user123";- let page = 1;- let page_size = 10;- let from = page * page_size;-- // When using SearchOn::Content on projects, it will search the "content" field- // But projects don't have a content field, they only have project_name- // The query builds successfully but is semantically invalid - it searches a non-existent field- let reference = serde_json::json!({- "query": {- "bool": {- "should": [- {- "terms": {- "project_id": project_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "content": terms[0]- }- },- ],- "minimum_should_match": 1- }- },- ],- }- },- "from": from,- "size": page_size,- "sort": [- {- "updated_at_seconds": {- "order": "desc"- }- },- {- "project_id": {- "order": "asc"- }- }- ],- "highlight": {- "fields": {- "project_name": {- "type": "unified",- "number_of_fragments": 500,- "pre_tags": ["<macro_em>"],- "post_tags": ["</macro_em>"],- "require_field_match": true,- }- }- },- });-- let generated = ProjectQueryBuilder::new(terms)- .match_type("exact")- .page_size(page_size)- .page(page)- .user_id(user_id)- .ids(project_ids)- .ids_only(true)- .search_on(SearchOn::Content)- .build()- .unwrap();-- assert_eq!(&generated, &reference);-}+mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/projects/test.rs b/rust/cloud-storage/opensearch_client/src/search/projects/test.rsnew file mode 100644index 0000000000..202119faf7--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/projects/test.rs@@ -0,0 +1,54 @@+use super::*;+use opensearch_query_builder::ToOpenSearchJson;++#[test]+fn test_build_search_request() -> anyhow::Result<()> {+ let builder = ProjectQueryBuilder::new(vec!["test".to_string()])+ .match_type("exact")+ .page_size(20)+ .page(1)+ .user_id("user123")+ .search_on(SearchOn::Name)+ .collapse(true)+ .ids(vec!["proj1".to_string(), "proj2".to_string()]);++ let result = builder.build_search_request()?;++ let expected = serde_json::json!({+ "from": 20,+ "size": 20,+ "collapse": {+ "field": "project_id"+ },+ "sort": ProjectSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ "highlight": ProjectSearchConfig::default_highlight().to_json(),+ "query": {+ "bool": {+ "must": [+ {+ "match_phrase": {+ "project_name": "test"+ }+ },+ ],+ "should": [+ {+ "terms": {+ "project_id": ["proj1", "proj2"]+ }+ },+ {+ "term": {+ "user_id": "user123"+ }+ }+ ],+ "minimum_should_match": 1,+ }+ }+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/search/query.rs b/rust/cloud-storage/opensearch_client/src/search/query.rsindex 69977ed286..c160584d24 100644--- a/rust/cloud-storage/opensearch_client/src/search/query.rs+++ b/rust/cloud-storage/opensearch_client/src/search/query.rs@@ -1,20 +1,26 @@+//! This module contains the logic for generating queries using terms+use crate::{Result, error::OpensearchClientError};-use crate::SearchOn;use opensearch_query_builder::*;use unicode_segmentation::UnicodeSegmentation;+/// Containing keys for the title and content fieldspub struct Keys<'a> {- pub id_key: &'a str,- pub user_id_key: &'a str,+ /// The title field keypub title_key: &'a str,+ /// The content field keypub content_key: &'a str,}-#[derive(Debug, Clone, Copy)]+/// The different types of ways we can match terms+#[derive(Debug, Clone, Copy, PartialEq)]pub enum QueryKey {+ /// Match phraseMatchPhrase,+ /// Match phrase prefixMatchPhrasePrefix,+ /// RegexpRegexp,}@@ -37,7 +43,7 @@ impl QueryKey {}/// Creates a query given a field and term- fn create_query(&self, field: &str, term: &str) -> QueryType {+ pub fn create_query(&self, field: &str, term: &str) -> QueryType {// 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<_>>();@@ -63,13 +69,18 @@ impl QueryKey {Self::Regexp => QueryType::Regexp(RegexpQuery::new(field, &first_part_of_term)),};- let second_term_query =- QueryType::WildCard(WildcardQuery::new(field, last_part_of_term));+ let second_term_query = QueryType::WildCard(WildcardQuery::new(+ field,+ &format!("*{}*", last_part_of_term.to_lowercase()),+ true,+ ));++ let mut bool_query = QueryType::bool_query();- return QueryType::bool_query()- .must(first_term_query)- .must(second_term_query)- .build();+ bool_query.must(first_term_query);+ bool_query.must(second_term_query);++ return bool_query.build().into();}match self {@@ -83,8 +94,14 @@ impl QueryKey {}/// Generate the terms for the "must" query-fn generate_terms_must_query(query_key: QueryKey, fields: &[&str], terms: &[String]) -> QueryType {- let mut terms_must_query = BoolQueryBuilder::new().minimum_should_match(1);+pub(crate) fn generate_terms_must_query(+ query_key: QueryKey,+ fields: &[&str],+ terms: &[String],+) -> QueryType {+ let mut terms_must_query = BoolQueryBuilder::new();++ terms_must_query.minimum_should_match(1);// Map terms to querieslet queries: Vec<_> = fields@@ -92,586 +109,72 @@ fn generate_terms_must_query(query_key: QueryKey, fields: &[&str], terms: &[Stri.flat_map(|field| terms.iter().map(|term| query_key.create_query(field, term))).collect();- // populate in in "should" field+ // If we only have 1 query returned, we can just return that singular query+ // to go into the main bool must+ if queries.len() == 1 {+ return queries[0].clone();+ }++ // Otherwise, we need to add all the queries to a new bool should in order to properly search+ // over multiple termsfor query in queries {- terms_must_query = terms_must_query.should(query);+ terms_must_query.should(query);}- terms_must_query.build()+ terms_must_query.build().into()}-/// Builds the basic query object that can be used to search any index-/// This is meant to be expanded upon by specific search functions-pub(crate) fn build_top_level_bool(- terms: &[String],- match_type: &str,- keys: Keys,- ids: &[String],- user_id: &str,- search_on: SearchOn,- ids_only: bool,-) -> Result<BoolQueryBuilder> {- let query_key = QueryKey::from_match_type(match_type)?;-- // Only populate must array if there are terms, otherwise leave it empty- let mut must_array = Vec::new();- // TODO: we should error herer if terms is empty- if !terms.is_empty() {- // Determine which fields to search based on search_on parameter- let search_fields: Vec<&str> = match search_on {- SearchOn::Name => vec![keys.title_key],- SearchOn::Content => vec![keys.content_key],- SearchOn::NameContent => {- todo!("search on name content not implemented yet");- }- };+/// Generates the term queries SearchOn::NameContent+pub(crate) fn generate_name_content_query(keys: &Keys, terms: &[String]) -> QueryType {+ let mut terms_must_query = BoolQueryBuilder::new();- let terms_must_query = generate_terms_must_query(query_key, &search_fields, terms);- // NOTE: this array is always going to be a length of one- must_array.push(terms_must_query);- }+ terms_must_query.minimum_should_match(1);- let mut query_object = BoolQueryBuilder::new().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);++ bool_query.should(QueryType::MatchPhrasePrefix(+ MatchPhrasePrefixQuery::new(keys.title_key, term).boost(1000.0),+ ));++ bool_query.should(QueryType::MatchPhrasePrefix(+ MatchPhrasePrefixQuery::new(keys.content_key, term).boost(900.0),+ ));++ bool_query.should(QueryType::Match(+ MatchQuery::new(keys.title_key, term)+ .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, term)+ .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 !ids_only {- query_object = query_object.should(QueryType::term(keys.user_id_key, user_id));+ // 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();}- query_object = query_object.should(QueryType::terms(keys.id_key, ids.to_vec()));- for item in must_array {- query_object = query_object.must(item);+ // 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);}- Ok(query_object)+ terms_must_query.build().into()}#[cfg(test)]-mod tests {- use super::*;-- fn build_basic_query_object(- terms: &[String],- match_type: &str,- keys: Keys,- ids: &[String],- user_id: &str,- search_on: SearchOn,- ids_only: bool,- ) -> Result<QueryType> {- let query_object =- build_top_level_bool(terms, match_type, keys, ids, user_id, search_on, ids_only)?;- let query_object = query_object.build();- Ok(query_object)- }-- #[test]- fn test_generate_terms_must_query_single_field_single_term() {- let terms = vec!["test".to_string()];-- let result = generate_terms_must_query(QueryKey::MatchPhrase, &["content"], &terms);-- let expected = serde_json::json!({- "bool": {- "should": [- {- "match_phrase": {- "content": "test"- }- },- ],- "minimum_should_match": 1- }- });-- assert_eq!(result.to_json(), expected);- }-- #[test]- fn test_generate_terms_must_query_single_field_multiple_terms() {- let terms = vec!["test".to_string(), "test2".to_string()];-- let result = generate_terms_must_query(QueryKey::MatchPhrase, &["content"], &terms);-- let expected = serde_json::json!({- "bool": {- "should": [- {- "match_phrase": {- "content": "test"- }- },- {- "match_phrase": {- "content": "test2"- }- },- ],- "minimum_should_match": 1- }- });-- assert_eq!(result.to_json(), expected);- }-- #[test]- fn test_generate_terms_must_query_multiple_field() {- let terms = vec!["test".to_string()];-- let result =- generate_terms_must_query(QueryKey::MatchPhrase, &["content", "subject"], &terms);-- let expected = serde_json::json!({- "bool": {- "should": [- {- "match_phrase": {- "content": "test"- }- },- {- "match_phrase": {- "subject": "test"- }- },- ],- "minimum_should_match": 1- }- });-- assert_eq!(result.to_json(), expected);- }-- #[test]- fn test_generate_terms_must_query_multiple_field_multiple_terms() {- let terms = vec!["test".to_string(), "test2".to_string()];-- let result =- generate_terms_must_query(QueryKey::MatchPhrase, &["content", "subject"], &terms);-- let expected = serde_json::json!({- "bool": {- "should": [- {- "match_phrase": {- "content": "test"- }- },- {- "match_phrase": {- "content": "test2"- }- },- {- "match_phrase": {- "subject": "test"- }- },- {- "match_phrase": {- "subject": "test2"- }- },- ],- "minimum_should_match": 1- }- });-- assert_eq!(result.to_json(), expected);- }-- #[test]- fn test_build_simple_query() {- let document_ids = ["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let terms = vec!["test".to_string()];- let reference = serde_json::json!({- "bool": {- "should": [- {- "term": {- "owner_id": user_id- }- },- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "content": terms[0],- }- },- ],- "minimum_should_match": 1- }- },- ],- }- });-- let keys = Keys {- id_key: "document_id",- user_id_key: "owner_id",- title_key: "document_name",- content_key: "content",- };-- let generated = build_basic_query_object(- &terms,- "exact",- keys,- &document_ids,- user_id,- SearchOn::Content,- false,- )- .unwrap();-- assert_eq!(&generated.to_json(), &reference);- }-- #[test]- fn test_build_simple_query_multiple_terms() {- let document_ids = ["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let terms = vec!["test".to_string(), "test2".to_string()];- let reference = serde_json::json!({- "bool": {- "should": [- {- "term": {- "owner_id": user_id- }- },- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "content": terms[0],- }- },- {- "match_phrase": {- "content": terms[1],- }- },- ],- "minimum_should_match": 1- }- },- ],- }- });-- let keys = Keys {- id_key: "document_id",- user_id_key: "owner_id",- title_key: "document_name",- content_key: "content",- };-- let generated = build_basic_query_object(- &terms,- "exact",- keys,- &document_ids,- user_id,- SearchOn::Content,- false,- )- .unwrap();-- assert_eq!(&generated.to_json(), &reference);- }-- #[test]- fn test_build_regexp_query_multiple_terms() {- let document_ids = ["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let terms = vec!["test".to_string(), "test2".to_string()];- let reference = serde_json::json!({- "bool": {- "should": [- {- "term": {- "owner_id": user_id- }- },- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "regexp": {- "content": {- "value": terms[0],- }- }- },- {- "regexp": {- "content": {- "value": terms[1],- }- }- },- ],- "minimum_should_match": 1- }- },- ],- }- });-- let keys = Keys {- id_key: "document_id",- user_id_key: "owner_id",- title_key: "document_name",- content_key: "content",- };-- let generated = build_basic_query_object(- &terms,- "regexp",- keys,- &document_ids,- user_id,- SearchOn::Content,- false,- )- .unwrap();-- assert_eq!(&generated.to_json(), &reference);- }-- #[test]- fn test_build_with_ids_only() {- let document_ids = ["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let terms = vec!["test".to_string(), "test2".to_string()];- let reference = serde_json::json!({- "bool": {- "should": [- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "regexp": {- "content": {- "value": terms[0],- }- }- },- {- "regexp": {- "content": {- "value": terms[1],- }- }- },- ],- "minimum_should_match": 1- }- },- ],- }- });-- let keys = Keys {- id_key: "document_id",- user_id_key: "owner_id",- title_key: "document_name",- content_key: "content",- };-- let generated = build_basic_query_object(- &terms,- "regexp",- keys,- &document_ids,- user_id,- SearchOn::Content,- true,- )- .unwrap();-- assert_eq!(&generated.to_json(), &reference);- }-- #[test]- fn test_build_name_search_query() {- let document_ids = ["A".to_string(), "B".to_string(), "C".to_string()];- let user_id = "user";- let terms = vec!["test".to_string(), "test2".to_string()];- let reference = serde_json::json!({- "bool": {- "should": [- {- "term": {- "owner_id": user_id- }- },- {- "terms": {- "document_id": document_ids- }- }- ],- "minimum_should_match": 1,- "must": [- {- "bool": {- "should": [- {- "match_phrase": {- "document_name": terms[0],- }- },- {- "match_phrase": {- "document_name": terms[1],- }- },- ],- "minimum_should_match": 1- }- },- ],- }- });-- let keys = Keys {- id_key: "document_id",- user_id_key: "owner_id",- title_key: "document_name",- content_key: "content",- };-- let generated = build_basic_query_object(- &terms,- "exact",- keys,- &document_ids,- user_id,- SearchOn::Name,- false,- )- .unwrap();-- assert_eq!(&generated.to_json(), &reference);- }-- /// Validates fix for https://linear.app/macro-eng/issue/M-5094/unified-search-match-prefix-on-phrase-should-not-constrain-terms- #[test]- fn test_create_query_with_short_last_term() {- let query_key = QueryKey::from_match_type("partial").unwrap();-- let result = QueryKey::create_query(&query_key, "subject", "person one re").to_json();-- assert_eq!(- result,- serde_json::json!({- "bool": {- "must": [- {- "match_phrase_prefix": {- "subject": {- "query": "person one"- }- }- },- {- "wildcard": {- "subject": {- "value": "*re*",- "case_insensitive": true- }- }- }- ]- }- })- );-- let result = QueryKey::create_query(&query_key, "subject", "person one 🦀").to_json();- assert_eq!(- result,- serde_json::json!({- "bool": {- "must": [- {- "match_phrase_prefix": {- "subject": {- "query": "person one"- }- }- },- {- "wildcard": {- "subject": {- "value": "*🦀*",- "case_insensitive": true- }- }- }- ]- }- })- );-- let result = QueryKey::create_query(&query_key, "subject", "person one").to_json();- assert_eq!(- result,- serde_json::json!({- "match_phrase_prefix": {- "subject": {- "query": "person one"- }- }- })- );-- let result = QueryKey::create_query(&query_key, "subject", "person one ").to_json();- assert_eq!(- result,- serde_json::json!({- "match_phrase_prefix": {- "subject": {- "query": "person one "- }- }- })- );- }-}+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.rsnew file mode 100644index 0000000000..f4f2ab5305--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/query/test.rs@@ -0,0 +1,274 @@+use super::*;++use opensearch_query_builder::ToOpenSearchJson;++#[test]+fn test_query_key_from_match_type() -> anyhow::Result<()> {+ assert_eq!(QueryKey::from_match_type("exact")?, QueryKey::MatchPhrase);+ assert_eq!(+ QueryKey::from_match_type("partial")?,+ QueryKey::MatchPhrasePrefix+ );+ assert_eq!(QueryKey::from_match_type("regexp")?, QueryKey::Regexp);++ let error = QueryKey::from_match_type("invalid").unwrap_err();++ assert_eq!(+ error,+ OpensearchClientError::InvalidMatchType {+ match_type: "invalid".to_string()+ }+ );++ Ok(())+}++#[test]+fn test_query_key_create_query() -> anyhow::Result<()> {+ let field = "test";+ let term = "test";+ let query_key = QueryKey::from_match_type("exact")?;++ let expected = serde_json::json!({+ "match_phrase": {+ "test": "test"+ }+ });++ let result = query_key.create_query(field, term).to_json();++ assert_eq!(result, expected);++ Ok(())+}++#[test]+fn test_query_key_short_last_word() -> anyhow::Result<()> {+ let field = "test";+ let term = "test Ab";++ let expected = serde_json::json!({+ "bool": {+ "must": [+ {+ "match_phrase_prefix": {+ "test": {+ "query": "test",+ }+ }+ },+ {+ "wildcard": {+ "test": {+ "case_insensitive": true,+ "value": "*ab*",+ }+ }+ }+ ]+ }+ });++ let result = QueryKey::MatchPhrasePrefix+ .create_query(field, term)+ .to_json();++ assert_eq!(result, expected);++ Ok(())+}++#[test]+fn test_generate_terms_must_query() -> anyhow::Result<()> {+ let result = generate_terms_must_query(QueryKey::MatchPhrase, &["test"], &["test".to_string()]);++ let expected = serde_json::json!({+ "match_phrase": {+ "test": "test"+ }+ });++ assert_eq!(result.to_json(), expected);++ let result = generate_terms_must_query(+ QueryKey::MatchPhrasePrefix,+ &["test"],+ &["test".to_string(), "test2".to_string()],+ );++ let expected = serde_json::json!({+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase_prefix": {+ "test": {+ "query": "test",+ }+ }+ },+ {+ "match_phrase_prefix": {+ "test": {+ "query": "test2",+ }+ }+ }+ ]+ }+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}++#[test]+fn test_generate_name_content_query() -> anyhow::Result<()> {+ let keys = Keys {+ title_key: "test_title",+ content_key: "test_content",+ };++ let result = generate_name_content_query(&keys, &["test".to_string()]);++ let expected = serde_json::json!({+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase_prefix": {+ "test_title": {+ "query": "test",+ "boost": 1000.0+ }+ }+ },+ {+ "match_phrase_prefix": {+ "test_content": {+ "query": "test",+ "boost": 900.0+ }+ }+ },+ {+ "match": {+ "test_title": {+ "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"+ }+ }+ }+ ]+ }+ }+ ]+ }+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/search/utils.rs b/rust/cloud-storage/opensearch_client/src/search/utils.rsindex b3dcece606..b044c1c28a 100644--- a/rust/cloud-storage/opensearch_client/src/search/utils.rs+++ b/rust/cloud-storage/opensearch_client/src/search/utils.rs@@ -1,79 +1,18 @@use opensearch_query_builder::{BoolQueryBuilder, QueryType, WildcardQuery};pub fn should_wildcard_field_query_builder(field: &str, values: &[String]) -> QueryType {- let mut should_query = BoolQueryBuilder::new().minimum_should_match(1);+ let mut should_query = BoolQueryBuilder::new();+ should_query.minimum_should_match(1);let wildcard_queries: Vec<WildcardQuery> = values.iter()- .map(|value| WildcardQuery::new(field, value).case_insensitive(true))+ .map(|value| WildcardQuery::new(field, &format!("*{}*", value.to_lowercase()), true)).collect();for query in wildcard_queries {- should_query = should_query.should(QueryType::WildCard(query));+ should_query.should(QueryType::WildCard(query));}- should_query.build()+ should_query.build().into()}#[cfg(test)]-mod tests {- use super::*;- use opensearch_query_builder::ToOpenSearchJson;-- #[test]- fn test_should_wildcard_field_query_builder_single_value() {- let field = "role";- let values = vec!["user".to_string()];-- let expected = serde_json::json!({- "bool": {- "should": [- {- "wildcard": {- "role": {- "value": "*user*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1- }- });-- let result = should_wildcard_field_query_builder(field, &values).to_json();- assert_eq!(result, expected);- }-- #[test]- fn test_should_wildcard_field_query_builder() {- // Test multiple values with mixed case and empty array- let field = "sender";- let values = vec!["User".to_string(), "ADMIN".to_string()];-- let expected = serde_json::json!({- "bool": {- "should": [- {- "wildcard": {- "sender": {- "value": "*user*",- "case_insensitive": true- }- }- },- {- "wildcard": {- "sender": {- "value": "*admin*",- "case_insensitive": true- }- }- }- ],- "minimum_should_match": 1- }- });-- let result = should_wildcard_field_query_builder(field, &values).to_json();- assert_eq!(result, expected);- }-}+mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/utils/test.rs b/rust/cloud-storage/opensearch_client/src/search/utils/test.rsnew file mode 100644index 0000000000..a5ac109420--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/utils/test.rs@@ -0,0 +1,61 @@+use super::*;+use opensearch_query_builder::ToOpenSearchJson;++#[test]+fn test_should_wildcard_field_query_builder_single_value() {+ let field = "role";+ let values = vec!["user".to_string()];++ let expected = serde_json::json!({+ "bool": {+ "should": [+ {+ "wildcard": {+ "role": {+ "value": "*user*",+ "case_insensitive": true+ }+ }+ }+ ],+ "minimum_should_match": 1+ }+ });++ let result = should_wildcard_field_query_builder(field, &values).to_json();+ assert_eq!(result, expected);+}++#[test]+fn test_should_wildcard_field_query_builder() {+ // Test multiple values with mixed case and empty array+ let field = "sender";+ let values = vec!["User".to_string(), "ADMIN".to_string()];++ let expected = serde_json::json!({+ "bool": {+ "should": [+ {+ "wildcard": {+ "sender": {+ "value": "*user*",+ "case_insensitive": true+ }+ }+ },+ {+ "wildcard": {+ "sender": {+ "value": "*admin*",+ "case_insensitive": true+ }+ }+ }+ ],+ "minimum_should_match": 1+ }+ });++ let result = should_wildcard_field_query_builder(field, &values).to_json();+ assert_eq!(result, expected);+}diff --git a/rust/cloud-storage/search_service/src/api/search/mod.rs b/rust/cloud-storage/search_service/src/api/search/mod.rsindex b2415bc4a0..b8cb8f39c6 100644--- a/rust/cloud-storage/search_service/src/api/search/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/mod.rs@@ -23,6 +23,6 @@ pub fn router() -> Router<ApiContext> {#[derive(serde::Serialize, serde::Deserialize, Debug)]pub struct SearchPaginationParams {- pub page: Option<i64>,- pub page_size: Option<i64>,+ pub page: Option<u32>,+ pub page_size: Option<u32>,}