Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore: import openserach query builder + update deps (#1925)

gbirmand93937fb9376
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 84f190d945..35ee025dd6 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -6776,9 +6776,7 @@ dependencies = [
[[package]]
name = "opensearch_query_builder"
-version = "0.2.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88471616dad533248e2ed35df90a076887afcbc000b0913739797fa7fea5df1a"
+version = "0.1.0"
dependencies = [
"serde",
"serde_json",
diff --git a/rust/cloud-storage/opensearch_client/Cargo.toml b/rust/cloud-storage/opensearch_client/Cargo.toml
index 8982588e9f..80253a3e9d 100644
--- a/rust/cloud-storage/opensearch_client/Cargo.toml
+++ b/rust/cloud-storage/opensearch_client/Cargo.toml
@@ -17,7 +17,7 @@ chrono = { workspace = true }
models_opensearch = { path = "../models_opensearch" }
models_search_cursor = { path = "../models_search_cursor" }
opensearch = { version = "2.3.0" }
-opensearch_query_builder = { version = "0.2.8", default-features = false }
+opensearch_query_builder = { path = "../opensearch_query_builder", default-features = false }
serde = { workspace = true }
serde_json = { workspace = true }
strum = { workspace = true }
diff --git a/rust/cloud-storage/opensearch_query_builder/.gitignore b/rust/cloud-storage/opensearch_query_builder/.gitignore
new file mode 100644
index 0000000000..8dd6e04f3e
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/.gitignore
@@ -0,0 +1,3 @@
+/target
+output/
+/.direnv
diff --git a/rust/cloud-storage/opensearch_query_builder/Cargo.toml b/rust/cloud-storage/opensearch_query_builder/Cargo.toml
new file mode 100644
index 0000000000..c3ea4ee6a3
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+edition = "2024"
+name = "opensearch_query_builder"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+serde = { workspace = true }
+serde_json = { workspace = true }
diff --git a/rust/cloud-storage/opensearch_query_builder/LICENSE b/rust/cloud-storage/opensearch_query_builder/LICENSE
new file mode 100644
index 0000000000..8e8c26e0b1
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 William Hutchinson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/rust/cloud-storage/opensearch_query_builder/README.md b/rust/cloud-storage/opensearch_query_builder/README.md
new file mode 100644
index 0000000000..15c45088fb
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/README.md
@@ -0,0 +1,3 @@
+# Opensearch Query Builder
+
+A Rust library for safely building Opensearch queries.
diff --git a/rust/cloud-storage/opensearch_query_builder/docker-compose.yml b/rust/cloud-storage/opensearch_query_builder/docker-compose.yml
new file mode 100644
index 0000000000..c7a3089118
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/docker-compose.yml
@@ -0,0 +1,70 @@
+version: '3.8'
+services:
+ opensearch-node1:
+ image: opensearchproject/opensearch:latest
+ container_name: opensearch-node1
+ environment:
+ - cluster.name=opensearch-cluster # Name the cluster
+ - node.name=opensearch-node1 # Name the node that will run in this container
+ - discovery.seed_hosts=opensearch-node1,opensearch-node2 # Nodes to look for when discovering the cluster
+ - cluster.initial_cluster_manager_nodes=opensearch-node1,opensearch-node2 # Nodes eligibile to serve as cluster manager
+ - bootstrap.memory_lock=true # Disable JVM heap memory swapping
+ - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # Set min and max JVM heap sizes to at least 50% of system RAM
+ - "DISABLE_INSTALL_DEMO_CONFIG=true" # Prevents execution of bundled demo script which installs demo certificates and security configurations to OpenSearch
+ - "DISABLE_SECURITY_PLUGIN=true" # Disables Security plugin
+ ulimits:
+ memlock:
+ soft: -1 # Set memlock to unlimited (no soft or hard limit)
+ hard: -1
+ nofile:
+ soft: 65536 # Maximum number of open files for the opensearch user - set to at least 65536
+ hard: 65536
+ volumes:
+ - opensearch-data1:/usr/share/opensearch/data # Creates volume called opensearch-data1 and mounts it to the container
+ ports:
+ - 9200:9200 # REST API
+ - 9600:9600 # Performance Analyzer
+ networks:
+ - opensearch-net # All of the containers will join the same Docker bridge network
+ opensearch-node2:
+ image: opensearchproject/opensearch:latest
+ container_name: opensearch-node2
+ environment:
+ - cluster.name=opensearch-cluster # Name the cluster
+ - node.name=opensearch-node2 # Name the node that will run in this container
+ - discovery.seed_hosts=opensearch-node1,opensearch-node2 # Nodes to look for when discovering the cluster
+ - cluster.initial_cluster_manager_nodes=opensearch-node1,opensearch-node2 # Nodes eligibile to serve as cluster manager
+ - bootstrap.memory_lock=true # Disable JVM heap memory swapping
+ - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # Set min and max JVM heap sizes to at least 50% of system RAM
+ - "DISABLE_INSTALL_DEMO_CONFIG=true" # Prevents execution of bundled demo script which installs demo certificates and security configurations to OpenSearch
+ - "DISABLE_SECURITY_PLUGIN=true" # Disables Security plugin
+ ulimits:
+ memlock:
+ soft: -1 # Set memlock to unlimited (no soft or hard limit)
+ hard: -1
+ nofile:
+ soft: 65536 # Maximum number of open files for the opensearch user - set to at least 65536
+ hard: 65536
+ volumes:
+ - opensearch-data2:/usr/share/opensearch/data # Creates volume called opensearch-data2 and mounts it to the container
+ networks:
+ - opensearch-net # All of the containers will join the same Docker bridge network
+ opensearch-dashboards:
+ image: opensearchproject/opensearch-dashboards:latest
+ container_name: opensearch-dashboards
+ ports:
+ - 5601:5601 # Map host port 5601 to container port 5601
+ expose:
+ - "5601" # Expose port 5601 for web access to OpenSearch Dashboards
+ environment:
+ - 'OPENSEARCH_HOSTS=["http://opensearch-node1:9200","http://opensearch-node2:9200"]'
+ - "DISABLE_SECURITY_DASHBOARDS_PLUGIN=true" # disables security dashboards plugin in OpenSearch Dashboards
+ networks:
+ - opensearch-net
+
+volumes:
+ opensearch-data1:
+ opensearch-data2:
+
+networks:
+ opensearch-net:
diff --git a/rust/cloud-storage/opensearch_query_builder/examples/basic_search_request.rs b/rust/cloud-storage/opensearch_query_builder/examples/basic_search_request.rs
new file mode 100644
index 0000000000..f74a472c42
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/examples/basic_search_request.rs
@@ -0,0 +1,66 @@
+use opensearch_query_builder::*;
+
+pub fn main() {
+ let page = 1;
+ let page_size = 2;
+ let from = page * page_size;
+ let query = "testing";
+ let mut bool_query = BoolQueryBuilder::new();
+
+ bool_query
+ .should(QueryType::term("content", query))
+ .minimum_should_match(1);
+
+ let result = SearchRequest::default()
+ .query(bool_query.build().into())
+ .from(from)
+ .size(page_size)
+ .sort(SortType::Field(FieldSort::new(
+ "updated_at",
+ SortOrder::Desc,
+ )))
+ .highlight(
+ Highlight::new().field(
+ "content",
+ HighlightField::new()
+ .highlight_type("unified")
+ .number_of_fragments(500)
+ .pre_tags(["<macro_em>"])
+ .post_tags(["</macro_em>"]),
+ ),
+ );
+
+ let reference = serde_json::json!({
+ "query": {
+ "bool": {
+ "should": [
+ {
+ "term": {
+ "content": query
+ }
+ },
+ ],
+ "minimum_should_match": 1
+ }
+ },
+ "from": from,
+ "size": page_size,
+ "sort": [
+ {
+ "updated_at": "desc",
+ },
+ ],
+ "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
+ }
+ }
+ },
+ });
+
+ assert_eq!(result.to_json(), reference);
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/examples/basic_search_request_builder.rs b/rust/cloud-storage/opensearch_query_builder/examples/basic_search_request_builder.rs
new file mode 100644
index 0000000000..e51988dd93
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/examples/basic_search_request_builder.rs
@@ -0,0 +1,71 @@
+use opensearch_query_builder::*;
+
+pub fn main() {
+ let page = 1;
+ let page_size = 2;
+ let from = page * page_size;
+ let query = "testing";
+ let mut bool_query = BoolQueryBuilder::new();
+
+ bool_query
+ .should(QueryType::term("content", query))
+ .minimum_should_match(1);
+
+ let mut search_request = SearchRequestBuilder::new();
+
+ search_request.query(bool_query.build().into());
+
+ search_request.from(from).size(page_size);
+
+ search_request.add_sort(SortType::Field(FieldSort::new(
+ "updated_at",
+ SortOrder::Desc,
+ )));
+
+ search_request.highlight(
+ Highlight::new().field(
+ "content",
+ HighlightField::new()
+ .highlight_type("unified")
+ .number_of_fragments(500)
+ .pre_tags(["<macro_em>"])
+ .post_tags(["</macro_em>"]),
+ ),
+ );
+
+ let result = search_request.build();
+
+ let reference = serde_json::json!({
+ "query": {
+ "bool": {
+ "should": [
+ {
+ "term": {
+ "content": query
+ }
+ },
+ ],
+ "minimum_should_match": 1
+ }
+ },
+ "from": from,
+ "size": page_size,
+ "sort": [
+ {
+ "updated_at": "desc",
+ },
+ ],
+ "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
+ }
+ }
+ },
+ });
+
+ assert_eq!(result.to_json(), reference);
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/lib.rs b/rust/cloud-storage/opensearch_query_builder/src/lib.rs
new file mode 100644
index 0000000000..499374b52e
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/lib.rs
@@ -0,0 +1,15 @@
+#![deny(missing_docs)]
+//! This crate provides a simple way to dynamically build OpenSearch queries in a type-safe manner.
+
+/// Trait for converting a Rust struct to an OpenSearch JSON object.
+pub trait ToOpenSearchJson {
+ /// Converts the struct to an OpenSearch JSON object.
+ fn to_json(&self) -> serde_json::Value;
+}
+
+mod query;
+mod request;
+mod util;
+
+pub use query::*;
+pub use request::*;
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query.rs b/rust/cloud-storage/opensearch_query_builder/src/query.rs
new file mode 100644
index 0000000000..2ddfbaf65c
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query.rs
@@ -0,0 +1,148 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+
+mod bool;
+mod function_score;
+mod match_phrase;
+mod match_phrase_prefix;
+mod match_query;
+mod range;
+mod regexp;
+mod term;
+mod terms;
+mod wildcard;
+
+pub use bool::*;
+pub use function_score::*;
+pub use match_phrase::*;
+pub use match_phrase_prefix::*;
+pub use match_query::*;
+pub use range::*;
+pub use regexp::*;
+use serde_json::Value;
+pub use term::*;
+pub use terms::*;
+pub use wildcard::*;
+
+use crate::ToOpenSearchJson;
+
+/// Enum representing the different types of queries that can be used in a search request.
+#[derive(Debug, Clone, Serialize)]
+#[serde(tag = "type", content = "params")]
+pub enum QueryType<'a> {
+ /// Bool query
+ Bool(BoolQuery<'a>),
+ /// Function score query
+ FunctionScore(FunctionScoreQuery<'a>),
+ /// Match phrase query
+ MatchPhrase(MatchPhraseQuery<'a>),
+ /// Match phrase prefix query
+ MatchPhrasePrefix(MatchPhrasePrefixQuery<'a>),
+ /// Match query
+ Match(MatchQuery<'a>),
+ /// Range query
+ Range(RangeQuery<'a>),
+ /// Regexp query
+ Regexp(RegexpQuery<'a>),
+ /// Term query
+ Term(TermQuery<'a>),
+ /// Terms query
+ Terms(TermsQuery<'a>),
+ /// Wildcard query
+ WildCard(WildcardQuery<'a>),
+}
+
+impl<'a> ToOpenSearchJson for QueryType<'a> {
+ fn to_json(&self) -> Value {
+ match self {
+ QueryType::Bool(bool_query) => bool_query.to_json(),
+ QueryType::FunctionScore(function_score) => function_score.to_json(),
+ QueryType::MatchPhrase(match_phrase) => match_phrase.to_json(),
+ QueryType::MatchPhrasePrefix(match_phrase_prefix) => match_phrase_prefix.to_json(),
+ QueryType::Match(match_query) => match_query.to_json(),
+ QueryType::Term(term) => term.to_json(),
+ QueryType::Terms(terms) => terms.to_json(),
+ QueryType::Range(range) => range.to_json(),
+ QueryType::WildCard(wildcard_query) => wildcard_query.to_json(),
+ QueryType::Regexp(regexp_query) => regexp_query.to_json(),
+ }
+ }
+}
+
+impl<'a> QueryType<'a> {
+ /// Convenience method for creating a term query
+ pub fn term<T: Into<Value>>(field: impl Into<Cow<'a, str>>, value: T) -> Self {
+ QueryType::Term(TermQuery::new(field, value))
+ }
+
+ /// Convenience method for creating a terms query
+ pub fn terms<T: Into<Value>>(
+ field: impl Into<Cow<'a, str>>,
+ values: impl IntoIterator<Item = T>,
+ ) -> Self {
+ QueryType::Terms(TermsQuery::new(field, values))
+ }
+
+ /// Convenience method for creating a wildcard query
+ pub fn wildcard(
+ field: impl Into<Cow<'a, str>>,
+ value: impl Into<Cow<'a, str>>,
+ case_insensitive: bool,
+ ) -> Self {
+ QueryType::WildCard(WildcardQuery::new(field, value, case_insensitive, None))
+ }
+
+ /// Convenience method for creating a regexp query
+ pub fn regexp(field: impl Into<Cow<'a, str>>, value: impl Into<Cow<'a, str>>) -> Self {
+ QueryType::Regexp(RegexpQuery::new(field, value))
+ }
+
+ /// Convenience method for creating a match query
+ pub fn match_phrase(field: impl Into<Cow<'a, str>>, query: impl Into<Cow<'a, str>>) -> Self {
+ QueryType::MatchPhrase(MatchPhraseQuery::new(field, query))
+ }
+
+ /// Convenience method for creating a match phrase prefix query
+ pub fn match_phrase_prefix(
+ field: impl Into<Cow<'a, str>>,
+ query: impl Into<Cow<'a, str>>,
+ ) -> Self {
+ QueryType::MatchPhrasePrefix(MatchPhrasePrefixQuery::new(field, query))
+ }
+
+ /// Convenience method for starting a bool query
+ pub fn bool_query() -> BoolQueryBuilder<'a> {
+ BoolQueryBuilder::new()
+ }
+
+ /// Convenience method for starting a match query
+ pub fn range(field: impl Into<Cow<'a, str>>) -> RangeQueryBuilder<'a> {
+ RangeQueryBuilder::new(field)
+ }
+
+ /// Convenience method for starting a function score query
+ pub fn function_score() -> FunctionScoreQueryBuilder<'a> {
+ FunctionScoreQueryBuilder::new()
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> QueryType<'static> {
+ match self {
+ QueryType::Bool(bool_query) => QueryType::Bool(bool_query.to_owned()),
+ QueryType::FunctionScore(function_score) => {
+ QueryType::FunctionScore(function_score.to_owned())
+ }
+ QueryType::MatchPhrase(match_phrase) => QueryType::MatchPhrase(match_phrase.to_owned()),
+ QueryType::MatchPhrasePrefix(match_phrase_prefix) => {
+ QueryType::MatchPhrasePrefix(match_phrase_prefix.to_owned())
+ }
+ QueryType::Match(match_query) => QueryType::Match(match_query.to_owned()),
+ QueryType::Range(range) => QueryType::Range(range.to_owned()),
+ QueryType::Regexp(regexp) => QueryType::Regexp(regexp.to_owned()),
+ QueryType::Term(term) => QueryType::Term(term.to_owned()),
+ QueryType::Terms(terms) => QueryType::Terms(terms.to_owned()),
+ QueryType::WildCard(wildcard) => QueryType::WildCard(wildcard.to_owned()),
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/bool.rs b/rust/cloud-storage/opensearch_query_builder/src/query/bool.rs
new file mode 100644
index 0000000000..10a11c3534
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/bool.rs
@@ -0,0 +1,200 @@
+use crate::util::is_empty_slice;
+use serde::Serialize;
+use serde_json::{Map, Value};
+use std::borrow::Cow;
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Bool Query
+#[derive(Default, Debug, Clone, Serialize)]
+pub struct BoolQuery<'a> {
+ /// Must queries
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub must: Cow<'a, [QueryType<'a>]>,
+ /// Must not queries
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub must_not: Cow<'a, [QueryType<'a>]>,
+ /// Should queries
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub should: Cow<'a, [QueryType<'a>]>,
+ /// Filter queries
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub filter: Cow<'a, [QueryType<'a>]>,
+ /// Minimum should match
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub minimum_should_match: Option<i32>,
+ /// Boost
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+}
+
+impl<'a> BoolQuery<'a> {
+ /// Create a new empty BoolQuery
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Add a must query
+ pub fn must(mut self, query: QueryType<'a>) -> Self {
+ self.must.to_mut().push(query);
+ self
+ }
+
+ /// Add a must not query
+ pub fn must_not(mut self, query: QueryType<'a>) -> Self {
+ self.must_not.to_mut().push(query);
+ self
+ }
+
+ /// Add a should query
+ pub fn should(mut self, query: QueryType<'a>) -> Self {
+ self.should.to_mut().push(query);
+ self
+ }
+
+ /// Add a filter query
+ pub fn filter(mut self, query: QueryType<'a>) -> Self {
+ self.filter.to_mut().push(query);
+ self
+ }
+
+ /// Set the minimum should match
+ pub fn minimum_should_match(mut self, min: i32) -> Self {
+ self.minimum_should_match = Some(min);
+ self
+ }
+
+ /// Set the boost
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> BoolQuery<'static> {
+ BoolQuery {
+ must: Cow::Owned(self.must.iter().map(|q| q.to_owned()).collect()),
+ must_not: Cow::Owned(self.must_not.iter().map(|q| q.to_owned()).collect()),
+ should: Cow::Owned(self.should.iter().map(|q| q.to_owned()).collect()),
+ filter: Cow::Owned(self.filter.iter().map(|q| q.to_owned()).collect()),
+ minimum_should_match: self.minimum_should_match,
+ boost: self.boost,
+ }
+ }
+}
+
+impl<'a> From<BoolQuery<'a>> for QueryType<'a> {
+ fn from(bool_query: BoolQuery<'a>) -> Self {
+ QueryType::Bool(bool_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for BoolQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut bool_obj = Map::new();
+
+ if !self.must.is_empty() {
+ let must_queries: Vec<Value> = self.must.iter().map(|q| q.to_json()).collect();
+ bool_obj.insert("must".to_string(), Value::Array(must_queries));
+ }
+
+ if !self.must_not.is_empty() {
+ let must_not_queries: Vec<Value> = self.must_not.iter().map(|q| q.to_json()).collect();
+ bool_obj.insert("must_not".to_string(), Value::Array(must_not_queries));
+ }
+
+ if !self.should.is_empty() {
+ let should_queries: Vec<Value> = self.should.iter().map(|q| q.to_json()).collect();
+ bool_obj.insert("should".to_string(), Value::Array(should_queries));
+ }
+
+ if !self.filter.is_empty() {
+ let filter_queries: Vec<Value> = self.filter.iter().map(|f| f.to_json()).collect();
+ bool_obj.insert("filter".to_string(), Value::Array(filter_queries));
+ }
+
+ if let Some(min) = self.minimum_should_match {
+ bool_obj.insert(
+ "minimum_should_match".to_string(),
+ Value::Number(min.into()),
+ );
+ }
+
+ if let Some(boost) = self.boost {
+ bool_obj.insert("boost".to_string(), boost.into());
+ }
+
+ let mut result = Map::new();
+ result.insert("bool".to_string(), Value::Object(bool_obj));
+ Value::Object(result)
+ }
+}
+
+/// Builder pattern for BoolQuery that allows dynamic updates.
+#[derive(Default, Debug, Clone)]
+pub struct BoolQueryBuilder<'a> {
+ must: Cow<'a, [QueryType<'a>]>,
+ must_not: Cow<'a, [QueryType<'a>]>,
+ should: Cow<'a, [QueryType<'a>]>,
+ filter: Cow<'a, [QueryType<'a>]>,
+ minimum_should_match: Option<i32>,
+ boost: Option<f64>,
+}
+
+impl<'a> BoolQueryBuilder<'a> {
+ /// Create a new empty BoolQueryBuilder
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Add a must query
+ pub fn must(&mut self, query: QueryType<'a>) -> &mut Self {
+ self.must.to_mut().push(query);
+ self
+ }
+
+ /// Add a must not query
+ pub fn must_not(&mut self, query: QueryType<'a>) -> &mut Self {
+ self.must_not.to_mut().push(query);
+ self
+ }
+
+ /// Add a should query
+ pub fn should(&mut self, query: QueryType<'a>) -> &mut Self {
+ self.should.to_mut().push(query);
+ self
+ }
+
+ /// Add a filter query
+ pub fn filter(&mut self, query: QueryType<'a>) -> &mut Self {
+ self.filter.to_mut().push(query);
+ self
+ }
+
+ /// Set the minimum should match
+ pub fn minimum_should_match(&mut self, min: i32) -> &mut Self {
+ self.minimum_should_match = Some(min);
+ self
+ }
+
+ /// Set the boost
+ pub fn boost(&mut self, boost: f64) -> &mut Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Build the final BoolQuery
+ pub fn build(self) -> BoolQuery<'a> {
+ BoolQuery {
+ must: self.must,
+ must_not: self.must_not,
+ should: self.should,
+ filter: self.filter,
+ minimum_should_match: self.minimum_should_match,
+ boost: self.boost,
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/bool/test.rs b/rust/cloud-storage/opensearch_query_builder/src/query/bool/test.rs
new file mode 100644
index 0000000000..22c0e319ac
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/bool/test.rs
@@ -0,0 +1,55 @@
+use crate::TermQuery;
+
+use super::*;
+
+#[test]
+fn test_bool_query_builder() {
+ let mut builder = BoolQueryBuilder::new();
+
+ builder
+ .must(QueryType::Term(TermQuery::new("a", "a")))
+ .must_not(QueryType::Term(TermQuery::new("c", "c")));
+
+ builder.must(QueryType::Term(TermQuery::new("b", "b")));
+
+ builder.should(QueryType::Term(TermQuery::new("d", "d")));
+
+ builder.minimum_should_match(1);
+
+ let result = builder.build().to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "bool": {
+ "must": [
+ {
+ "term": {
+ "a": "a"
+ }
+ },
+ {
+ "term": {
+ "b": "b"
+ }
+ }
+ ],
+ "must_not": [
+ {
+ "term": {
+ "c": "c"
+ }
+ }
+ ],
+ "should": [
+ {
+ "term": {
+ "d": "d"
+ }
+ }
+ ],
+ "minimum_should_match": 1
+ }
+ })
+ );
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score.rs
new file mode 100644
index 0000000000..b46e6068e9
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score.rs
@@ -0,0 +1,267 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+
+mod boost_mode;
+mod decay_function;
+mod field_value_factor;
+mod random_score;
+mod score_function;
+mod score_mode;
+mod script_score;
+
+pub use boost_mode::*;
+pub use decay_function::*;
+pub use field_value_factor::*;
+pub use random_score::*;
+pub use score_function::*;
+pub use score_mode::*;
+pub use script_score::*;
+use serde_json::{Map, Value};
+
+use crate::util::is_empty_slice;
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Function Score Query
+#[derive(Debug, Clone, Serialize, Default)]
+pub struct FunctionScoreQuery<'a> {
+ /// The query to use for scoring
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub query: Option<Box<QueryType<'a>>>,
+ /// The scoring functions to use
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub functions: Cow<'a, [ScoreFunction<'a>]>,
+ /// The score mode to use
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub score_mode: Option<ScoreMode>,
+ /// The boost mode to use
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost_mode: Option<BoostMode>,
+ /// The maximum boost to use
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max_boost: Option<f64>,
+ /// The boost to use
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+ /// The minimum score to use
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub min_score: Option<f64>,
+}
+
+impl<'a> FunctionScoreQuery<'a> {
+ /// Create a new empty FunctionScoreQuery
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set the query for this query
+ pub fn query(mut self, query: QueryType<'a>) -> Self {
+ self.query = Some(Box::new(query));
+ self
+ }
+
+ /// Add a scoring function
+ pub fn function(mut self, function: ScoreFunction<'a>) -> Self {
+ self.functions.to_mut().push(function);
+ self
+ }
+
+ /// Set the score mode
+ pub fn score_mode(mut self, score_mode: ScoreMode) -> Self {
+ self.score_mode = Some(score_mode);
+ self
+ }
+
+ /// Set the boost mode
+ pub fn boost_mode(mut self, boost_mode: BoostMode) -> Self {
+ self.boost_mode = Some(boost_mode);
+ self
+ }
+
+ /// Set the maximum boost
+ pub fn max_boost(mut self, max_boost: f64) -> Self {
+ self.max_boost = Some(max_boost);
+ self
+ }
+
+ /// Set the boost
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Set the minimum score
+ pub fn min_score(mut self, min_score: f64) -> Self {
+ self.min_score = Some(min_score);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> FunctionScoreQuery<'static> {
+ FunctionScoreQuery {
+ query: self.query.as_ref().map(|q| Box::new((**q).to_owned())),
+ functions: Cow::Owned(self.functions.iter().map(|f| f.to_owned()).collect()),
+ score_mode: self.score_mode.clone(),
+ boost_mode: self.boost_mode.clone(),
+ max_boost: self.max_boost,
+ boost: self.boost,
+ min_score: self.min_score,
+ }
+ }
+}
+
+impl<'a> From<FunctionScoreQuery<'a>> for QueryType<'a> {
+ fn from(function_score_query: FunctionScoreQuery<'a>) -> Self {
+ QueryType::FunctionScore(function_score_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for FunctionScoreQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut function_score_obj = Map::new();
+
+ // Add query if present
+ if let Some(ref query) = self.query {
+ function_score_obj.insert("query".to_string(), query.to_json());
+ }
+
+ // Add functions array if not empty
+ if !self.functions.is_empty() {
+ let functions: Vec<Value> = self.functions.iter().map(|f| f.to_json()).collect();
+ function_score_obj.insert("functions".to_string(), Value::Array(functions));
+ }
+
+ // Add score_mode if present
+ if let Some(ref score_mode) = self.score_mode {
+ function_score_obj.insert(
+ "score_mode".to_string(),
+ Value::String(match score_mode {
+ ScoreMode::Multiply => "multiply".to_string(),
+ ScoreMode::Sum => "sum".to_string(),
+ ScoreMode::Avg => "avg".to_string(),
+ ScoreMode::First => "first".to_string(),
+ ScoreMode::Max => "max".to_string(),
+ ScoreMode::Min => "min".to_string(),
+ }),
+ );
+ }
+
+ // Add boost_mode if present
+ if let Some(ref boost_mode) = self.boost_mode {
+ function_score_obj.insert(
+ "boost_mode".to_string(),
+ Value::String(match boost_mode {
+ BoostMode::Multiply => "multiply".to_string(),
+ BoostMode::Replace => "replace".to_string(),
+ BoostMode::Sum => "sum".to_string(),
+ BoostMode::Avg => "avg".to_string(),
+ BoostMode::Max => "max".to_string(),
+ BoostMode::Min => "min".to_string(),
+ }),
+ );
+ }
+
+ // Add max_boost if present
+ if let Some(max_boost) = self.max_boost {
+ function_score_obj.insert("max_boost".to_string(), max_boost.into());
+ }
+
+ // Add boost if present
+ if let Some(boost) = self.boost {
+ function_score_obj.insert("boost".to_string(), boost.into());
+ }
+
+ // Add min_score if present
+ if let Some(min_score) = self.min_score {
+ function_score_obj.insert("min_score".to_string(), min_score.into());
+ }
+
+ let mut result = Map::new();
+ result.insert(
+ "function_score".to_string(),
+ Value::Object(function_score_obj),
+ );
+ Value::Object(result)
+ }
+}
+
+/// Builder pattern for FunctionScoreQuery that allows dynamic updates.
+#[derive(Default)]
+pub struct FunctionScoreQueryBuilder<'a> {
+ /// The query to use for scoring
+ pub query: Option<Box<QueryType<'a>>>,
+ /// The scoring functions to use
+ pub functions: Cow<'a, [ScoreFunction<'a>]>,
+ /// The score mode to use
+ pub score_mode: Option<ScoreMode>,
+ /// The boost mode to use
+ pub boost_mode: Option<BoostMode>,
+ /// The maximum boost to use
+ pub max_boost: Option<f64>,
+ /// The boost to use
+ pub boost: Option<f64>,
+ /// The minimum score to use
+ pub min_score: Option<f64>,
+}
+
+impl<'a> FunctionScoreQueryBuilder<'a> {
+ /// Create a new empty FunctionScoreQueryBuilder
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set the query for this query (replaces existing query)
+ pub fn query(&mut self, query: QueryType<'a>) -> &mut Self {
+ self.query = Some(Box::new(query));
+ self
+ }
+
+ /// Add a scoring function (can be called multiple times)
+ pub fn function(&mut self, function: ScoreFunction<'a>) -> &mut Self {
+ self.functions.to_mut().push(function);
+ self
+ }
+
+ /// Set the score mode (replaces existing score mode)
+ pub fn score_mode(&mut self, score_mode: ScoreMode) -> &mut Self {
+ self.score_mode = Some(score_mode);
+ self
+ }
+
+ /// Set the boost mode (replaces existing boost mode)
+ pub fn boost_mode(&mut self, boost_mode: BoostMode) -> &mut Self {
+ self.boost_mode = Some(boost_mode);
+ self
+ }
+
+ /// Set the maximum boost (replaces existing maximum boost)
+ pub fn max_boost(&mut self, max_boost: f64) -> &mut Self {
+ self.max_boost = Some(max_boost);
+ self
+ }
+
+ /// Set the boost (replaces existing boost)
+ pub fn boost(&mut self, boost: f64) -> &mut Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Set the minimum score (replaces existing minimum score)
+ pub fn min_score(&mut self, min_score: f64) -> &mut Self {
+ self.min_score = Some(min_score);
+ self
+ }
+
+ /// Build the final FunctionScoreQuery
+ pub fn build(self) -> FunctionScoreQuery<'a> {
+ FunctionScoreQuery {
+ query: self.query,
+ functions: self.functions,
+ score_mode: self.score_mode,
+ boost_mode: self.boost_mode,
+ max_boost: self.max_boost,
+ boost: self.boost,
+ min_score: self.min_score,
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score/boost_mode.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/boost_mode.rs
new file mode 100644
index 0000000000..d6d9b27184
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/boost_mode.rs
@@ -0,0 +1,19 @@
+use serde::Serialize;
+
+/// Boost mode
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BoostMode {
+ /// Multiply the boost by the function's result
+ Multiply,
+ /// Replace the boost with the function's result
+ Replace,
+ /// Add the function's result to the boost
+ Sum,
+ /// Average the function's result with the boost
+ Avg,
+ /// Take the maximum of the function's result and the boost
+ Max,
+ /// Take the minimum of the function's result and the boost
+ Min,
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score/decay_function.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/decay_function.rs
new file mode 100644
index 0000000000..cc0b8145a7
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/decay_function.rs
@@ -0,0 +1,66 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::Value;
+
+/// Decay function configuration
+#[derive(Debug, Clone, Serialize)]
+pub struct DecayFunction<'a> {
+ /// The field to use for decaying
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The origin value to use for decaying
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub origin: Option<Value>,
+ /// The scale to use for decaying
+ #[serde(borrow)]
+ pub scale: Cow<'a, str>,
+ /// The offset to use for decaying
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub offset: Option<Cow<'a, str>>,
+ /// The decay to use for decaying
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub decay: Option<f64>,
+}
+
+impl<'a> DecayFunction<'a> {
+ /// Create a new DecayFunction
+ pub fn new(field: impl Into<Cow<'a, str>>, scale: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ origin: None,
+ scale: scale.into(),
+ offset: None,
+ decay: None,
+ }
+ }
+
+ /// Set the origin value
+ pub fn origin<T: Into<Value>>(mut self, origin: T) -> Self {
+ self.origin = Some(origin.into());
+ self
+ }
+
+ /// Set the offset
+ pub fn offset(mut self, offset: impl Into<Cow<'a, str>>) -> Self {
+ self.offset = Some(offset.into());
+ self
+ }
+
+ /// Set the decay
+ pub fn decay(mut self, decay: f64) -> Self {
+ self.decay = Some(decay);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> DecayFunction<'static> {
+ DecayFunction {
+ field: Cow::Owned(self.field.to_string()),
+ origin: self.origin.clone(),
+ scale: Cow::Owned(self.scale.to_string()),
+ offset: self.offset.as_ref().map(|o| Cow::Owned(o.to_string())),
+ decay: self.decay,
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score/field_value_factor.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/field_value_factor.rs
new file mode 100644
index 0000000000..a67f3e2282
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/field_value_factor.rs
@@ -0,0 +1,60 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+
+/// Field value factor configuration
+#[derive(Debug, Clone, Serialize)]
+pub struct FieldValueFactor<'a> {
+ /// The field to use for factoring
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The factor to use for factoring
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub factor: Option<f64>,
+ /// The modifier to use for factoring
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub modifier: Option<Cow<'a, str>>,
+ /// The missing value to use for factoring
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub missing: Option<f64>,
+}
+
+impl<'a> FieldValueFactor<'a> {
+ /// Create a new FieldValueFactor
+ pub fn new(field: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ factor: None,
+ modifier: None,
+ missing: None,
+ }
+ }
+
+ /// Set the factor
+ pub fn factor(mut self, factor: f64) -> Self {
+ self.factor = Some(factor);
+ self
+ }
+
+ /// Set the modifier
+ pub fn modifier(mut self, modifier: impl Into<Cow<'a, str>>) -> Self {
+ self.modifier = Some(modifier.into());
+ self
+ }
+
+ /// Set the missing value
+ pub fn missing(mut self, missing: f64) -> Self {
+ self.missing = Some(missing);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> FieldValueFactor<'static> {
+ FieldValueFactor {
+ field: Cow::Owned(self.field.to_string()),
+ factor: self.factor,
+ modifier: self.modifier.as_ref().map(|m| Cow::Owned(m.to_string())),
+ missing: self.missing,
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score/random_score.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/random_score.rs
new file mode 100644
index 0000000000..c84477518d
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/random_score.rs
@@ -0,0 +1,42 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::Value;
+
+/// Random score configuration
+#[derive(Debug, Clone, Serialize, Default)]
+pub struct RandomScore<'a> {
+ /// The seed to use for randomizing
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub seed: Option<Value>,
+ /// The field to use for randomizing
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub field: Option<Cow<'a, str>>,
+}
+
+impl<'a> RandomScore<'a> {
+ /// Create a new empty RandomScore
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set the seed
+ pub fn seed<T: Into<Value>>(mut self, seed: T) -> Self {
+ self.seed = Some(seed.into());
+ self
+ }
+
+ /// Set the field
+ pub fn field(mut self, field: impl Into<Cow<'a, str>>) -> Self {
+ self.field = Some(field.into());
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> RandomScore<'static> {
+ RandomScore {
+ seed: self.seed.clone(),
+ field: self.field.as_ref().map(|f| Cow::Owned(f.to_string())),
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score/score_function.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/score_function.rs
new file mode 100644
index 0000000000..74b9e7e6a3
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/score_function.rs
@@ -0,0 +1,181 @@
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{
+ DecayFunction, FieldValueFactor, QueryType, RandomScore, ScriptScore, ToOpenSearchJson,
+};
+
+/// Enum representing different scoring functions
+#[derive(Debug, Clone, Serialize)]
+#[serde(untagged)]
+pub enum ScoreFunctionType<'a> {
+ /// Gauss decay function
+ Gauss(DecayFunction<'a>),
+ /// Exp decay function
+ Exp(DecayFunction<'a>),
+ /// Linear decay function
+ Linear(DecayFunction<'a>),
+ /// Field value factor function
+ FieldValueFactor(FieldValueFactor<'a>),
+ /// Random score function
+ RandomScore(RandomScore<'a>),
+ /// Script score function
+ ScriptScore(ScriptScore<'a>),
+ /// Weight function
+ Weight(f64),
+}
+
+impl<'a> ScoreFunctionType<'a> {
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> ScoreFunctionType<'static> {
+ match self {
+ ScoreFunctionType::Gauss(decay) => ScoreFunctionType::Gauss(decay.to_owned()),
+ ScoreFunctionType::Exp(decay) => ScoreFunctionType::Exp(decay.to_owned()),
+ ScoreFunctionType::Linear(decay) => ScoreFunctionType::Linear(decay.to_owned()),
+ ScoreFunctionType::FieldValueFactor(fvf) => {
+ ScoreFunctionType::FieldValueFactor(fvf.to_owned())
+ }
+ ScoreFunctionType::RandomScore(rs) => ScoreFunctionType::RandomScore(rs.to_owned()),
+ ScoreFunctionType::ScriptScore(ss) => ScoreFunctionType::ScriptScore(ss.to_owned()),
+ ScoreFunctionType::Weight(w) => ScoreFunctionType::Weight(*w),
+ }
+ }
+}
+
+/// A single scoring function with optional filter and weight
+#[derive(Debug, Clone, Serialize)]
+pub struct ScoreFunction<'a> {
+ /// The scoring function
+ #[serde(flatten)]
+ pub function: ScoreFunctionType<'a>,
+ /// The filter to apply to the function
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub filter: Option<Box<QueryType<'a>>>,
+ /// The weight to apply to the function
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub weight: Option<f64>,
+}
+
+impl<'a> ScoreFunction<'a> {
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> ScoreFunction<'static> {
+ ScoreFunction {
+ function: self.function.to_owned(),
+ filter: self.filter.as_ref().map(|f| Box::new((**f).to_owned())),
+ weight: self.weight,
+ }
+ }
+}
+
+impl<'a> ToOpenSearchJson for ScoreFunction<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+
+ // Add the function type
+ match &self.function {
+ ScoreFunctionType::Gauss(decay) => {
+ let mut decay_obj = Map::new();
+ let mut field_obj = Map::new();
+
+ if let Some(ref origin) = decay.origin {
+ field_obj.insert("origin".to_string(), origin.clone());
+ }
+ field_obj.insert("scale".to_string(), Value::String(decay.scale.to_string()));
+ if let Some(ref offset) = decay.offset {
+ field_obj.insert("offset".to_string(), Value::String(offset.to_string()));
+ }
+ if let Some(decay_val) = decay.decay {
+ field_obj.insert("decay".to_string(), decay_val.into());
+ }
+
+ decay_obj.insert(decay.field.to_string(), Value::Object(field_obj));
+ result.insert("gauss".to_string(), Value::Object(decay_obj));
+ }
+ ScoreFunctionType::Exp(decay) => {
+ let mut decay_obj = Map::new();
+ let mut field_obj = Map::new();
+
+ if let Some(ref origin) = decay.origin {
+ field_obj.insert("origin".to_string(), origin.clone());
+ }
+ field_obj.insert("scale".to_string(), Value::String(decay.scale.to_string()));
+ if let Some(ref offset) = decay.offset {
+ field_obj.insert("offset".to_string(), Value::String(offset.to_string()));
+ }
+ if let Some(decay_val) = decay.decay {
+ field_obj.insert("decay".to_string(), decay_val.into());
+ }
+
+ decay_obj.insert(decay.field.to_string(), Value::Object(field_obj));
+ result.insert("exp".to_string(), Value::Object(decay_obj));
+ }
+ ScoreFunctionType::Linear(decay) => {
+ let mut decay_obj = Map::new();
+ let mut field_obj = Map::new();
+
+ if let Some(ref origin) = decay.origin {
+ field_obj.insert("origin".to_string(), origin.clone());
+ }
+ field_obj.insert("scale".to_string(), Value::String(decay.scale.to_string()));
+ if let Some(ref offset) = decay.offset {
+ field_obj.insert("offset".to_string(), Value::String(offset.to_string()));
+ }
+ if let Some(decay_val) = decay.decay {
+ field_obj.insert("decay".to_string(), decay_val.into());
+ }
+
+ decay_obj.insert(decay.field.to_string(), Value::Object(field_obj));
+ result.insert("linear".to_string(), Value::Object(decay_obj));
+ }
+ ScoreFunctionType::FieldValueFactor(fvf) => {
+ let mut fvf_obj = Map::new();
+ fvf_obj.insert("field".to_string(), Value::String(fvf.field.to_string()));
+ if let Some(factor) = fvf.factor {
+ fvf_obj.insert("factor".to_string(), factor.into());
+ }
+ if let Some(ref modifier) = fvf.modifier {
+ fvf_obj.insert("modifier".to_string(), Value::String(modifier.to_string()));
+ }
+ if let Some(missing) = fvf.missing {
+ fvf_obj.insert("missing".to_string(), missing.into());
+ }
+ result.insert("field_value_factor".to_string(), Value::Object(fvf_obj));
+ }
+ ScoreFunctionType::RandomScore(rs) => {
+ let mut rs_obj = Map::new();
+ if let Some(ref seed) = rs.seed {
+ rs_obj.insert("seed".to_string(), seed.clone());
+ }
+ if let Some(ref field) = rs.field {
+ rs_obj.insert("field".to_string(), Value::String(field.to_string()));
+ }
+ result.insert("random_score".to_string(), Value::Object(rs_obj));
+ }
+ ScoreFunctionType::ScriptScore(ss) => {
+ let mut script_obj = Map::new();
+ script_obj.insert("source".to_string(), Value::String(ss.source.to_string()));
+ if let Some(ref params) = ss.params {
+ script_obj.insert("params".to_string(), Value::Object(params.clone()));
+ }
+ let mut ss_obj = Map::new();
+ ss_obj.insert("script".to_string(), Value::Object(script_obj));
+ result.insert("script_score".to_string(), Value::Object(ss_obj));
+ }
+ ScoreFunctionType::Weight(_) => {
+ // Weight-only functions don't add a function type field
+ }
+ }
+
+ // Add filter if present
+ if let Some(ref filter) = self.filter {
+ result.insert("filter".to_string(), filter.to_json());
+ }
+
+ // Add weight if present
+ if let Some(weight) = self.weight {
+ result.insert("weight".to_string(), weight.into());
+ }
+
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score/score_mode.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/score_mode.rs
new file mode 100644
index 0000000000..b679b8ac78
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/score_mode.rs
@@ -0,0 +1,19 @@
+use serde::Serialize;
+
+/// Score mode
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ScoreMode {
+ /// Multiply the score by the function's result
+ Multiply,
+ /// Add the function's result to the score
+ Sum,
+ /// Average the function's result with the score
+ Avg,
+ /// Take the minimum of the function's result and the score
+ First,
+ /// Take the maximum of the function's result and the score
+ Max,
+ /// Take the minimum of the function's result and the score
+ Min,
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/function_score/script_score.rs b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/script_score.rs
new file mode 100644
index 0000000000..5c50b46dcb
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/function_score/script_score.rs
@@ -0,0 +1,39 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+/// Script score configuration
+#[derive(Debug, Clone, Serialize)]
+pub struct ScriptScore<'a> {
+ /// The script to use for scoring
+ #[serde(borrow)]
+ pub source: Cow<'a, str>,
+ /// The parameters to use for scoring
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub params: Option<Map<String, Value>>,
+}
+
+impl<'a> ScriptScore<'a> {
+ /// Create a new ScriptScore
+ pub fn new(source: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ source: source.into(),
+ params: None,
+ }
+ }
+
+ /// Set the parameters
+ pub fn params(mut self, params: Map<String, Value>) -> Self {
+ self.params = Some(params);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> ScriptScore<'static> {
+ ScriptScore {
+ source: Cow::Owned(self.source.to_string()),
+ params: self.params.clone(),
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/match_phrase.rs b/rust/cloud-storage/opensearch_query_builder/src/query/match_phrase.rs
new file mode 100644
index 0000000000..8659067f14
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/match_phrase.rs
@@ -0,0 +1,112 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Match Phrase Query
+#[derive(Debug, Clone, Serialize)]
+pub struct MatchPhraseQuery<'a> {
+ /// The field to search
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The query string
+ #[serde(borrow)]
+ pub query: Cow<'a, str>,
+ /// The slop value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub slop: Option<u32>,
+ /// The analyzer to use
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(borrow)]
+ pub analyzer: Option<Cow<'a, str>>,
+ /// The boost value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+}
+
+impl<'a> MatchPhraseQuery<'a> {
+ /// Create a new MatchPhraseQuery with a given field and query string
+ pub fn new(field: impl Into<Cow<'a, str>>, query: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ query: query.into(),
+ analyzer: None,
+ slop: None,
+ boost: None,
+ }
+ }
+
+ /// Set the slop value
+ pub fn slop(mut self, slop: u32) -> Self {
+ self.slop = Some(slop);
+ self
+ }
+
+ /// Set the analyzer to use
+ pub fn analyzer(mut self, analyzer: impl Into<Cow<'a, str>>) -> Self {
+ self.analyzer = Some(analyzer.into());
+ self
+ }
+
+ /// Set the boost value
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> MatchPhraseQuery<'static> {
+ MatchPhraseQuery {
+ field: Cow::Owned(self.field.to_string()),
+ query: Cow::Owned(self.query.to_string()),
+ slop: self.slop,
+ analyzer: self.analyzer.as_ref().map(|a| Cow::Owned(a.to_string())),
+ boost: self.boost,
+ }
+ }
+}
+
+impl<'a> From<MatchPhraseQuery<'a>> for QueryType<'a> {
+ fn from(match_phrase_query: MatchPhraseQuery<'a>) -> Self {
+ QueryType::MatchPhrase(match_phrase_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for MatchPhraseQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ let mut match_phrase_obj = Map::new();
+
+ // Check if we need the complex form
+ let has_options = self.slop.is_some() || self.analyzer.is_some() || self.boost.is_some();
+
+ if has_options {
+ // Complex form with options
+ let mut field_obj = Map::new();
+ field_obj.insert("query".to_string(), Value::String(self.query.to_string()));
+
+ if let Some(analyzer) = self.analyzer.as_ref() {
+ field_obj.insert("analyzer".to_string(), Value::String(analyzer.to_string()));
+ }
+ if let Some(slop) = self.slop {
+ field_obj.insert("slop".to_string(), Value::Number(slop.into()));
+ }
+ if let Some(boost) = self.boost {
+ field_obj.insert("boost".to_string(), boost.into());
+ }
+
+ match_phrase_obj.insert(self.field.to_string(), Value::Object(field_obj));
+ } else {
+ // Simple form: just field: "query"
+ match_phrase_obj.insert(
+ self.field.to_string(),
+ Value::String(self.query.to_string()),
+ );
+ }
+
+ result.insert("match_phrase".to_string(), Value::Object(match_phrase_obj));
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/match_phrase_prefix.rs b/rust/cloud-storage/opensearch_query_builder/src/query/match_phrase_prefix.rs
new file mode 100644
index 0000000000..0c09cbb27a
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/match_phrase_prefix.rs
@@ -0,0 +1,106 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Match Phrase Prefix Query
+#[derive(Debug, Clone, Serialize)]
+pub struct MatchPhrasePrefixQuery<'a> {
+ /// The field to search
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The query string
+ #[serde(borrow)]
+ pub query: Cow<'a, str>,
+ /// The maximum number of terms that can be expanded upon
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max_expansions: Option<u32>,
+ /// The slop value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub slop: Option<u32>,
+ /// The boost value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+}
+
+impl<'a> MatchPhrasePrefixQuery<'a> {
+ /// Create a new MatchPhrasePrefixQuery with a given field and query string
+ pub fn new(field: impl Into<Cow<'a, str>>, query: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ query: query.into(),
+ max_expansions: None,
+ slop: None,
+ boost: None,
+ }
+ }
+
+ /// Set the maximum number of terms that can be expanded upon
+ pub fn max_expansions(mut self, max_expansions: u32) -> Self {
+ self.max_expansions = Some(max_expansions);
+ self
+ }
+
+ /// Set the slop value
+ pub fn slop(mut self, slop: u32) -> Self {
+ self.slop = Some(slop);
+ self
+ }
+
+ /// Set the boost value
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> MatchPhrasePrefixQuery<'static> {
+ MatchPhrasePrefixQuery {
+ field: Cow::Owned(self.field.to_string()),
+ query: Cow::Owned(self.query.to_string()),
+ max_expansions: self.max_expansions,
+ slop: self.slop,
+ boost: self.boost,
+ }
+ }
+}
+
+impl<'a> From<MatchPhrasePrefixQuery<'a>> for QueryType<'a> {
+ fn from(match_phrase_prefix_query: MatchPhrasePrefixQuery<'a>) -> Self {
+ QueryType::MatchPhrasePrefix(match_phrase_prefix_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for MatchPhrasePrefixQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ let mut match_phrase_prefix_obj = Map::new();
+ let mut field_obj = Map::new();
+
+ // Match phrase prefix always uses the complex form with "query" field
+ field_obj.insert("query".to_string(), Value::String(self.query.to_string()));
+
+ if let Some(max_expansions) = self.max_expansions {
+ field_obj.insert(
+ "max_expansions".to_string(),
+ Value::Number(max_expansions.into()),
+ );
+ }
+ if let Some(slop) = self.slop {
+ field_obj.insert("slop".to_string(), Value::Number(slop.into()));
+ }
+ if let Some(boost) = self.boost {
+ field_obj.insert("boost".to_string(), boost.into());
+ }
+
+ match_phrase_prefix_obj.insert(self.field.to_string(), Value::Object(field_obj));
+
+ result.insert(
+ "match_phrase_prefix".to_string(),
+ Value::Object(match_phrase_prefix_obj),
+ );
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/match_query.rs b/rust/cloud-storage/opensearch_query_builder/src/query/match_query.rs
new file mode 100644
index 0000000000..9f508a6dff
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/match_query.rs
@@ -0,0 +1,140 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Match Query
+#[derive(Debug, Clone, Serialize)]
+pub struct MatchQuery<'a> {
+ /// The field to search
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The query string
+ #[serde(borrow)]
+ pub query: Cow<'a, str>,
+ /// The operator to use
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(borrow)]
+ pub operator: Option<Cow<'a, str>>,
+ /// The fuzziness value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(borrow)]
+ pub fuzziness: Option<Cow<'a, str>>,
+ /// The boost value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+ /// The minimum should match value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(borrow)]
+ pub minimum_should_match: Option<Cow<'a, str>>,
+}
+
+impl<'a> MatchQuery<'a> {
+ /// Create a new MatchQuery with a given field and query string
+ pub fn new(field: impl Into<Cow<'a, str>>, query: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ query: query.into(),
+ operator: None,
+ fuzziness: None,
+ boost: None,
+ minimum_should_match: None,
+ }
+ }
+
+ /// Set the operator to use
+ pub fn operator(mut self, operator: impl Into<Cow<'a, str>>) -> Self {
+ self.operator = Some(operator.into());
+ self
+ }
+
+ /// Set the fuzziness value
+ pub fn fuzziness(mut self, fuzziness: impl Into<Cow<'a, str>>) -> Self {
+ self.fuzziness = Some(fuzziness.into());
+ self
+ }
+
+ /// Set the boost value
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Set the minimum should match value
+ pub fn minimum_should_match(mut self, minimum_should_match: impl Into<Cow<'a, str>>) -> Self {
+ self.minimum_should_match = Some(minimum_should_match.into());
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> MatchQuery<'static> {
+ MatchQuery {
+ field: Cow::Owned(self.field.to_string()),
+ query: Cow::Owned(self.query.to_string()),
+ operator: self.operator.as_ref().map(|o| Cow::Owned(o.to_string())),
+ fuzziness: self.fuzziness.as_ref().map(|f| Cow::Owned(f.to_string())),
+ boost: self.boost,
+ minimum_should_match: self
+ .minimum_should_match
+ .as_ref()
+ .map(|m| Cow::Owned(m.to_string())),
+ }
+ }
+}
+
+impl<'a> From<MatchQuery<'a>> for QueryType<'a> {
+ fn from(match_query: MatchQuery<'a>) -> Self {
+ QueryType::Match(match_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for MatchQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ let mut match_obj = Map::new();
+
+ // Check if we need the complex form
+ let has_options = self.operator.is_some()
+ || self.fuzziness.is_some()
+ || self.boost.is_some()
+ || self.minimum_should_match.is_some();
+
+ if has_options {
+ let mut field_obj = Map::new();
+ field_obj.insert("query".to_string(), Value::String(self.query.to_string()));
+
+ if let Some(ref operator) = self.operator {
+ field_obj.insert("operator".to_string(), Value::String(operator.to_string()));
+ }
+ if let Some(ref fuzziness) = self.fuzziness {
+ field_obj.insert(
+ "fuzziness".to_string(),
+ Value::String(fuzziness.to_string()),
+ );
+ }
+ if let Some(boost) = self.boost {
+ field_obj.insert("boost".to_string(), boost.into());
+ }
+
+ if let Some(ref minimum_should_match) = self.minimum_should_match {
+ field_obj.insert(
+ "minimum_should_match".to_string(),
+ Value::String(minimum_should_match.to_string()),
+ );
+ }
+
+ match_obj.insert(self.field.to_string(), Value::Object(field_obj));
+ } else {
+ // Simple form: field: "query"
+ match_obj.insert(
+ self.field.to_string(),
+ Value::String(self.query.to_string()),
+ );
+ }
+
+ result.insert("match".to_string(), Value::Object(match_obj));
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/range.rs b/rust/cloud-storage/opensearch_query_builder/src/query/range.rs
new file mode 100644
index 0000000000..2f887cc77e
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/range.rs
@@ -0,0 +1,190 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Range Query
+#[derive(Debug, Clone, Serialize)]
+pub struct RangeQuery<'a> {
+ /// The field to search
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// Greater than or equal to
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub gte: Option<Value>,
+ /// Greater than
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub gt: Option<Value>,
+ /// Less than or equal to
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lte: Option<Value>,
+ /// Less than
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lt: Option<Value>,
+ /// The boost value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+}
+
+impl<'a> RangeQuery<'a> {
+ /// Create a new RangeQuery with a given field
+ pub fn new(field: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ gte: None,
+ gt: None,
+ lte: None,
+ lt: None,
+ boost: None,
+ }
+ }
+
+ /// Sets the greater than or equal to value
+ pub fn gte<T: Into<Value>>(mut self, value: T) -> Self {
+ self.gte = Some(value.into());
+ self
+ }
+ /// Sets the greater than value
+ pub fn gt<T: Into<Value>>(mut self, value: T) -> Self {
+ self.gt = Some(value.into());
+ self
+ }
+ /// Sets the less than or equal to value
+ pub fn lte<T: Into<Value>>(mut self, value: T) -> Self {
+ self.lte = Some(value.into());
+ self
+ }
+ /// Sets the less than value
+ pub fn lt<T: Into<Value>>(mut self, value: T) -> Self {
+ self.lt = Some(value.into());
+ self
+ }
+
+ /// Set the boost value
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> RangeQuery<'static> {
+ RangeQuery {
+ field: Cow::Owned(self.field.to_string()),
+ gte: self.gte.clone(),
+ gt: self.gt.clone(),
+ lte: self.lte.clone(),
+ lt: self.lt.clone(),
+ boost: self.boost,
+ }
+ }
+}
+
+impl<'a> From<RangeQuery<'a>> for QueryType<'a> {
+ fn from(range_query: RangeQuery<'a>) -> Self {
+ QueryType::Range(range_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for RangeQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut range_obj = Map::new();
+ let mut field_obj = Map::new();
+
+ if let Some(ref gte) = self.gte {
+ field_obj.insert("gte".to_string(), gte.clone());
+ }
+ if let Some(ref gt) = self.gt {
+ field_obj.insert("gt".to_string(), gt.clone());
+ }
+ if let Some(ref lte) = self.lte {
+ field_obj.insert("lte".to_string(), lte.clone());
+ }
+ if let Some(ref lt) = self.lt {
+ field_obj.insert("lt".to_string(), lt.clone());
+ }
+ if let Some(boost) = self.boost {
+ field_obj.insert("boost".to_string(), boost.into());
+ }
+
+ range_obj.insert(self.field.to_string(), Value::Object(field_obj));
+
+ let mut result = Map::new();
+ result.insert("range".to_string(), Value::Object(range_obj));
+ Value::Object(result)
+ }
+}
+
+/// Builder pattern for RangeQuery that allows dynamic updates.
+pub struct RangeQueryBuilder<'a> {
+ /// The field to search
+ #[allow(dead_code)]
+ pub field: Cow<'a, str>,
+ /// Greater than or equal to
+ pub gte: Option<Value>,
+ /// Greater than
+ pub gt: Option<Value>,
+ /// Less than or equal to
+ pub lte: Option<Value>,
+ /// Less than
+ pub lt: Option<Value>,
+ /// The boost value
+ pub boost: Option<f64>,
+}
+
+impl<'a> RangeQueryBuilder<'a> {
+ /// Create a new empty RangeQueryBuilder
+ pub fn new(field: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ gte: None,
+ gt: None,
+ lte: None,
+ lt: None,
+ boost: None,
+ }
+ }
+
+ /// Sets the greater than or equal to value
+ pub fn gte<T: Into<Value>>(&mut self, value: T) -> &mut Self {
+ self.gte = Some(value.into());
+ self
+ }
+
+ /// Sets the greater than value
+ pub fn gt<T: Into<Value>>(&mut self, value: T) -> &mut Self {
+ self.gt = Some(value.into());
+ self
+ }
+
+ /// Sets the less than or equal to value
+ pub fn lte<T: Into<Value>>(&mut self, value: T) -> &mut Self {
+ self.lte = Some(value.into());
+ self
+ }
+
+ /// Sets the less than value
+ pub fn lt<T: Into<Value>>(&mut self, value: T) -> &mut Self {
+ self.lt = Some(value.into());
+ self
+ }
+
+ /// Set the boost value
+ pub fn boost(&mut self, boost: f64) -> &mut Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Build the final RangeQuery
+ pub fn build(self) -> RangeQuery<'a> {
+ RangeQuery {
+ field: self.field,
+ gte: self.gte,
+ gt: self.gt,
+ lte: self.lte,
+ lt: self.lt,
+ boost: self.boost,
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/regexp.rs b/rust/cloud-storage/opensearch_query_builder/src/query/regexp.rs
new file mode 100644
index 0000000000..9916b4b7ff
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/regexp.rs
@@ -0,0 +1,121 @@
+use std::{borrow::Cow, fmt::Display};
+
+use serde::Serialize;
+use serde_json::Value;
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Enum representing the different flags that can be used with a RegexpQuery
+#[derive(Debug, Clone, Serialize, Default)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum RegexpQueryFlags {
+ /// Enables all optional features (default behavior)
+ All,
+ /// Allows @ to match any string
+ Anystring,
+ /// Matches the complement of the language described by the regex
+ Complement,
+ /// Allows matching empty strings
+ Empty,
+ /// Enables intersection of multiple patterns
+ Intersection,
+ /// Enables interval arithmetic on character classes
+ Interval,
+ /// Disables all optional features (default behavior)
+ #[default]
+ None,
+}
+
+impl RegexpQueryFlags {
+ /// Create a new RegexpQueryFlags with the All flag
+ pub fn all() -> Vec<Self> {
+ vec![Self::All]
+ }
+}
+
+impl Display for RegexpQueryFlags {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ RegexpQueryFlags::All => write!(f, "ALL"),
+ RegexpQueryFlags::Anystring => write!(f, "ANYSTRING"),
+ RegexpQueryFlags::Complement => write!(f, "COMPLEMENT"),
+ RegexpQueryFlags::Empty => write!(f, "EMPTY"),
+ RegexpQueryFlags::Intersection => write!(f, "INTERSECTION"),
+ RegexpQueryFlags::Interval => write!(f, "INTERVAL"),
+ RegexpQueryFlags::None => write!(f, "NONE"),
+ }
+ }
+}
+
+/// Regexp Query
+#[derive(Debug, Clone, Serialize, Default)]
+pub struct RegexpQuery<'a> {
+ /// The field to search in
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The stringified regex pattern to match on
+ #[serde(borrow)]
+ pub value: Cow<'a, str>,
+ /// The flags to use when matching the regular expression
+ #[serde(borrow)]
+ pub flags: Option<Cow<'a, [RegexpQueryFlags]>>,
+}
+
+impl<'a> RegexpQuery<'a> {
+ /// Create a new RegexpQuery with a given field and value
+ pub fn new(field: impl Into<Cow<'a, str>>, value: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ value: value.into(),
+ flags: None,
+ }
+ }
+
+ /// Set the flags to use when matching the regular expression
+ pub fn flags(mut self, flags: Cow<'a, [RegexpQueryFlags]>) -> Self {
+ self.flags = Some(flags);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> RegexpQuery<'static> {
+ RegexpQuery {
+ field: Cow::Owned(self.field.to_string()),
+ value: Cow::Owned(self.value.to_string()),
+ flags: self.flags.as_ref().map(|f| Cow::Owned(f.to_vec())),
+ }
+ }
+}
+
+impl<'a> From<RegexpQuery<'a>> for QueryType<'a> {
+ fn from(regexp_query: RegexpQuery<'a>) -> Self {
+ QueryType::Regexp(regexp_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for RegexpQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut json = serde_json::json!({
+ "regexp": {
+ self.field.as_ref(): {
+ "value": self.value.as_ref(),
+ }
+ }
+ });
+
+ if let Some(flags) = self.flags.as_ref()
+ && !flags.is_empty()
+ {
+ // Join all flags with |
+ json["regexp"][self.field.as_ref()]["flags"] = Value::String(
+ flags
+ .iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join("|"),
+ );
+ }
+
+ json
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/term.rs b/rust/cloud-storage/opensearch_query_builder/src/query/term.rs
new file mode 100644
index 0000000000..e4bb01abf9
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/term.rs
@@ -0,0 +1,74 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Term Query
+#[derive(Debug, Clone, Serialize)]
+pub struct TermQuery<'a> {
+ /// The field to search
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The value to search for
+ pub value: Value,
+ /// The boost value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+}
+
+impl<'a> TermQuery<'a> {
+ /// Create a new TermQuery with a given field and value
+ pub fn new<T: Into<Value>>(field: impl Into<Cow<'a, str>>, value: T) -> Self {
+ Self {
+ field: field.into(),
+ value: value.into(),
+ boost: None,
+ }
+ }
+
+ /// Set the boost value
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> TermQuery<'static> {
+ TermQuery {
+ field: Cow::Owned(self.field.to_string()),
+ value: self.value.clone(),
+ boost: self.boost,
+ }
+ }
+}
+
+impl<'a> From<TermQuery<'a>> for QueryType<'a> {
+ fn from(term_query: TermQuery<'a>) -> Self {
+ QueryType::Term(term_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for TermQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ let mut term_obj = Map::new();
+
+ // If we have additional parameters like boost, use the object form
+ if self.boost.is_some() {
+ let mut field_obj = Map::new();
+ field_obj.insert("value".to_string(), self.value.clone());
+ if let Some(boost) = self.boost {
+ field_obj.insert("boost".to_string(), boost.into());
+ }
+ term_obj.insert(self.field.to_string(), Value::Object(field_obj));
+ } else {
+ // Simple form: just field: value
+ term_obj.insert(self.field.to_string(), self.value.clone());
+ }
+
+ result.insert("term".to_string(), Value::Object(term_obj));
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/terms.rs b/rust/cloud-storage/opensearch_query_builder/src/query/terms.rs
new file mode 100644
index 0000000000..0eda51bbb4
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/terms.rs
@@ -0,0 +1,78 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Terms Query
+#[derive(Debug, Clone, Serialize)]
+pub struct TermsQuery<'a> {
+ /// The field to search
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The values to search for
+ #[serde(borrow)]
+ pub values: Cow<'a, [Value]>,
+ /// The boost value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub boost: Option<f64>,
+}
+
+impl<'a> TermsQuery<'a> {
+ /// Create a new TermsQuery with a given field and values
+ pub fn new<T: Into<Value>>(
+ field: impl Into<Cow<'a, str>>,
+ values: impl IntoIterator<Item = T>,
+ ) -> Self {
+ Self {
+ field: field.into(),
+ values: Cow::Owned(values.into_iter().map(|v| v.into()).collect()),
+ boost: None,
+ }
+ }
+
+ /// Set the boost value
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> TermsQuery<'static> {
+ TermsQuery {
+ field: Cow::Owned(self.field.to_string()),
+ values: Cow::Owned(self.values.to_vec()),
+ boost: self.boost,
+ }
+ }
+}
+
+impl<'a> From<TermsQuery<'a>> for QueryType<'a> {
+ fn from(terms_query: TermsQuery<'a>) -> Self {
+ QueryType::Terms(terms_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for TermsQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ let mut terms_obj = Map::new();
+
+ if self.boost.is_some() {
+ // Complex form with boost
+ let mut field_obj = Map::new();
+ field_obj.insert("terms".to_string(), Value::Array(self.values.to_vec()));
+ if let Some(boost) = self.boost {
+ field_obj.insert("boost".to_string(), boost.into());
+ }
+ terms_obj.insert(self.field.to_string(), Value::Object(field_obj));
+ } else {
+ // Simple form: field: [values]
+ terms_obj.insert(self.field.to_string(), Value::Array(self.values.to_vec()));
+ }
+
+ result.insert("terms".to_string(), Value::Object(terms_obj));
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/wildcard.rs b/rust/cloud-storage/opensearch_query_builder/src/query/wildcard.rs
new file mode 100644
index 0000000000..6ef1919412
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/wildcard.rs
@@ -0,0 +1,84 @@
+use std::borrow::Cow;
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value};
+
+use crate::{QueryType, ToOpenSearchJson};
+
+/// Wildcard Query
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WildcardQuery<'a> {
+ /// The field to search
+ #[serde(borrow)]
+ field: Cow<'a, str>,
+ /// The value to search for
+ /// **NOTE**: You'll need to wrap the value in `*` yourself
+ #[serde(borrow)]
+ value: Cow<'a, str>,
+ /// Whether to perform a case-insensitive search
+ case_insensitive: bool,
+ /// The boost value
+ boost: Option<f64>,
+}
+
+impl<'a> WildcardQuery<'a> {
+ /// Create a new WildcardQuery with a given field, value, and case_insensitive flag
+ pub fn new(
+ field: impl Into<Cow<'a, str>>,
+ value: impl Into<Cow<'a, str>>,
+ case_insensitive: bool,
+ boost: Option<f64>,
+ ) -> Self {
+ Self {
+ field: field.into(),
+ value: value.into(),
+ case_insensitive,
+ boost,
+ }
+ }
+
+ /// Set the boost
+ pub fn boost(mut self, boost: f64) -> Self {
+ self.boost = Some(boost);
+ self
+ }
+
+ /// Convert to an owned version with 'static lifetime
+ pub fn to_owned(&self) -> WildcardQuery<'static> {
+ WildcardQuery {
+ field: Cow::Owned(self.field.to_string()),
+ value: Cow::Owned(self.value.to_string()),
+ case_insensitive: self.case_insensitive,
+ boost: self.boost,
+ }
+ }
+}
+
+impl<'a> From<WildcardQuery<'a>> for QueryType<'a> {
+ fn from(wildcard_query: WildcardQuery<'a>) -> Self {
+ QueryType::WildCard(wildcard_query)
+ }
+}
+
+impl<'a> ToOpenSearchJson for WildcardQuery<'a> {
+ fn to_json(&self) -> Value {
+ let mut wildcard_obj = Map::new();
+ let mut field_obj = Map::new();
+
+ field_obj.insert("value".to_string(), Value::String(self.value.to_string()));
+ field_obj.insert("case_insensitive".to_string(), self.case_insensitive.into());
+
+ if let Some(boost) = self.boost {
+ field_obj.insert("boost".to_string(), boost.into());
+ }
+
+ wildcard_obj.insert(self.field.to_string(), Value::Object(field_obj));
+
+ let mut result = Map::new();
+ result.insert("wildcard".to_string(), Value::Object(wildcard_obj));
+ Value::Object(result)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/wildcard/test.rs b/rust/cloud-storage/opensearch_query_builder/src/query/wildcard/test.rs
new file mode 100644
index 0000000000..7ef5bd2418
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/query/wildcard/test.rs
@@ -0,0 +1,38 @@
+use super::*;
+
+#[test]
+fn test_wildcard_query_without_boost() {
+ let query = WildcardQuery::new("name", "*john*", true, None);
+ let result = query.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "wildcard": {
+ "name": {
+ "value": "*john*",
+ "case_insensitive": true
+ }
+ }
+ })
+ );
+}
+
+#[test]
+fn test_wildcard_query_with_boost() {
+ let query = WildcardQuery::new("name", "*john*", false, Some(2.0));
+ let result = query.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "wildcard": {
+ "name": {
+ "value": "*john*",
+ "case_insensitive": false,
+ "boost": 2.0
+ }
+ }
+ })
+ );
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request.rs b/rust/cloud-storage/opensearch_query_builder/src/request.rs
new file mode 100644
index 0000000000..1bb3712605
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request.rs
@@ -0,0 +1,351 @@
+use std::borrow::Cow;
+use std::collections::HashMap;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::util::is_empty_slice;
+use crate::{QueryType, ToOpenSearchJson};
+
+mod aggregation_type;
+mod collapse;
+mod highlight;
+mod sort_type;
+
+pub use aggregation_type::*;
+pub use collapse::*;
+pub use highlight::*;
+pub use sort_type::*;
+
+/// Struct representing a search request.
+#[derive(Default, Debug, Clone, Serialize)]
+pub struct SearchRequest<'a> {
+ /// Query
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub query: Option<QueryType<'a>>,
+ /// Maximum number of results to return
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub size: Option<u32>,
+ /// Offset
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub from: Option<u32>,
+ /// Sort criteria
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub sort: Cow<'a, [SortType<'a>]>,
+ /// Aggregations
+ #[serde(skip_serializing_if = "HashMap::is_empty", default)]
+ #[serde(borrow)]
+ pub aggs: HashMap<Cow<'a, str>, AggregationType<'a>>,
+ /// Source fields
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub _source: Cow<'a, [Cow<'a, str>]>,
+ /// Highlight
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub highlight: Option<Highlight<'a>>,
+ /// Track total hits
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub track_total_hits: Option<bool>,
+ /// Collapse
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub collapse: Option<Collapse<'a>>,
+ /// Search after (cursor-based pagination)
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub search_after: Cow<'a, [Value]>,
+}
+
+impl<'a> SearchRequest<'a> {
+ /// Create a new SearchRequest
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set the query
+ pub fn query(mut self, query: QueryType<'a>) -> Self {
+ self.query = Some(query);
+ self
+ }
+
+ /// Set the maximum number of results to return
+ pub fn size(mut self, size: u32) -> Self {
+ self.size = Some(size);
+ self
+ }
+
+ /// Set the offset
+ pub fn from(mut self, from: u32) -> Self {
+ self.from = Some(from);
+ self
+ }
+
+ /// Add a sort criterion
+ pub fn sort(mut self, sort: SortType<'a>) -> Self {
+ self.sort.to_mut().push(sort);
+ self
+ }
+
+ /// Add an aggregation
+ pub fn agg(mut self, name: impl Into<Cow<'a, str>>, agg: AggregationType<'a>) -> Self {
+ self.aggs.insert(name.into(), agg);
+ self
+ }
+
+ /// Set source fields
+ pub fn source_fields<I>(mut self, fields: I) -> Self
+ where
+ I: IntoIterator,
+ I::Item: Into<Cow<'a, str>>,
+ {
+ self._source = fields.into_iter().map(|s| s.into()).collect();
+ self
+ }
+
+ /// Set the highlight configuration
+ pub fn highlight(mut self, highlight: Highlight<'a>) -> Self {
+ self.highlight = Some(highlight);
+ self
+ }
+
+ /// Set whether to track total hits
+ pub fn track_total_hits(mut self, track: bool) -> Self {
+ self.track_total_hits = Some(track);
+ self
+ }
+
+ /// Set the collapse configuration
+ pub fn collapse(mut self, collapse: Collapse<'a>) -> Self {
+ self.collapse = Some(collapse);
+ self
+ }
+
+ /// Set search_after for cursor-based pagination
+ pub fn search_after<I>(mut self, values: I) -> Self
+ where
+ I: Into<Cow<'a, [Value]>>,
+ {
+ self.search_after = values.into();
+ self
+ }
+}
+
+impl<'a> ToOpenSearchJson for SearchRequest<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+
+ if let Some(ref query) = self.query {
+ result.insert("query".to_string(), query.to_json());
+ }
+
+ if let Some(size) = self.size {
+ result.insert("size".to_string(), Value::Number(size.into()));
+ }
+
+ if let Some(from) = self.from {
+ result.insert("from".to_string(), Value::Number(from.into()));
+ }
+
+ if !self.sort.is_empty() {
+ let sorts: Vec<Value> = self.sort.iter().map(|s| s.to_json()).collect();
+ result.insert("sort".to_string(), Value::Array(sorts));
+ }
+
+ if !self.aggs.is_empty() {
+ let mut aggs_obj = Map::new();
+ for (name, agg) in &self.aggs {
+ aggs_obj.insert(name.to_string(), agg.to_json());
+ }
+ result.insert("aggs".to_string(), Value::Object(aggs_obj));
+ }
+
+ if !self._source.is_empty() {
+ let sources: Vec<Value> = self
+ ._source
+ .iter()
+ .map(|s| Value::String(s.to_string()))
+ .collect();
+ result.insert("_source".to_string(), Value::Array(sources));
+ }
+
+ if let Some(ref highlight) = self.highlight {
+ result.insert("highlight".to_string(), highlight.to_json());
+ }
+
+ if let Some(track_total_hits) = self.track_total_hits {
+ result.insert(
+ "track_total_hits".to_string(),
+ Value::Bool(track_total_hits),
+ );
+ }
+
+ if let Some(ref collapse) = self.collapse {
+ result.insert("collapse".to_string(), collapse.to_json());
+ }
+
+ if !self.search_after.is_empty() {
+ result.insert(
+ "search_after".to_string(),
+ Value::Array(self.search_after.to_vec()),
+ );
+ }
+
+ Value::Object(result)
+ }
+}
+
+/// Builder pattern for SearchRequest that allows dynamic updates.
+/// Unlike the fluent methods on SearchRequest, this builder uses mutable methods
+/// so you can dynamically add fields over time before calling build().
+#[derive(Default, Debug, Clone)]
+pub struct SearchRequestBuilder<'a> {
+ query: Option<QueryType<'a>>,
+ size: Option<u32>,
+ from: Option<u32>,
+ sort: Cow<'a, [SortType<'a>]>,
+ aggs: HashMap<Cow<'a, str>, AggregationType<'a>>,
+ _source: Cow<'a, [Cow<'a, str>]>,
+ highlight: Option<Highlight<'a>>,
+ track_total_hits: Option<bool>,
+ collapse: Option<Collapse<'a>>,
+ search_after: Cow<'a, [Value]>,
+}
+
+impl<'a> SearchRequestBuilder<'a> {
+ /// Create a new empty SearchRequestBuilder
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set the query for this search request
+ pub fn query(&mut self, query: QueryType<'a>) -> &mut Self {
+ self.query = Some(query);
+ self
+ }
+
+ /// Set the maximum number of results to return
+ pub fn size(&mut self, size: u32) -> &mut Self {
+ self.size = Some(size);
+ self
+ }
+
+ /// Set the offset for pagination
+ pub fn from(&mut self, from: u32) -> &mut Self {
+ self.from = Some(from);
+ self
+ }
+
+ /// Add a sort criterion (can be called multiple times)
+ pub fn add_sort(&mut self, sort: SortType<'a>) -> &mut Self {
+ self.sort.to_mut().push(sort);
+ self
+ }
+
+ /// Set all sort criteria at once (replaces existing sorts)
+ pub fn set_sorts(&mut self, sorts: Cow<'a, [SortType<'a>]>) -> &mut Self {
+ self.sort = sorts;
+ self
+ }
+
+ /// Clear all sort criteria
+ pub fn clear_sorts(&mut self) -> &mut Self {
+ self.sort = Cow::Borrowed(&[]);
+ self
+ }
+
+ /// Add an aggregation
+ pub fn add_agg(
+ &mut self,
+ name: impl Into<Cow<'a, str>>,
+ agg: AggregationType<'a>,
+ ) -> &mut Self {
+ self.aggs.insert(name.into(), agg);
+ self
+ }
+
+ /// Remove an aggregation by name
+ pub fn remove_agg(&mut self, name: impl Into<Cow<'a, str>>) -> &mut Self {
+ self.aggs.remove(&name.into());
+ self
+ }
+
+ /// Clear all aggregations
+ pub fn clear_aggs(&mut self) -> &mut Self {
+ self.aggs.clear();
+ self
+ }
+
+ /// Add a source field to include in the response
+ pub fn add_source_field(&mut self, field: impl Into<Cow<'a, str>>) -> &mut Self {
+ self._source.to_mut().push(field.into());
+ self
+ }
+
+ /// Set source fields (replaces existing fields)
+ pub fn set_source_fields<I>(&mut self, fields: I) -> &mut Self
+ where
+ I: IntoIterator,
+ I::Item: Into<Cow<'a, str>>,
+ {
+ self._source = fields.into_iter().map(|s| s.into()).collect();
+ self
+ }
+
+ /// Clear all source fields
+ pub fn clear_source_fields(&mut self) -> &mut Self {
+ self._source = Cow::Borrowed(&[]);
+ self
+ }
+
+ /// Set the highlight configuration
+ pub fn highlight(&mut self, highlight: Highlight<'a>) -> &mut Self {
+ self.highlight = Some(highlight);
+ self
+ }
+
+ /// Set whether to track total hits
+ pub fn track_total_hits(&mut self, track: bool) -> &mut Self {
+ self.track_total_hits = Some(track);
+ self
+ }
+
+ /// Set the collapse configuration
+ pub fn collapse(&mut self, collapse: Collapse<'a>) -> &mut Self {
+ self.collapse = Some(collapse);
+ self
+ }
+
+ /// Add a value to search_after for cursor-based pagination
+ pub fn add_search_after_value(&mut self, value: Value) -> &mut Self {
+ self.search_after.to_mut().push(value);
+ self
+ }
+
+ /// Set search_after values (replaces existing values)
+ pub fn set_search_after<I>(&mut self, values: I) -> &mut Self
+ where
+ I: Into<Cow<'a, [Value]>>,
+ {
+ self.search_after = values.into();
+ self
+ }
+
+ /// Clear all search_after values
+ pub fn clear_search_after(&mut self) -> &mut Self {
+ self.search_after = Cow::Borrowed(&[]);
+ self
+ }
+
+ /// Build the final SearchRequest
+ pub fn build(self) -> SearchRequest<'a> {
+ SearchRequest {
+ query: self.query,
+ size: self.size,
+ from: self.from,
+ sort: self.sort,
+ aggs: self.aggs,
+ _source: self._source,
+ highlight: self.highlight,
+ track_total_hits: self.track_total_hits,
+ collapse: self.collapse,
+ search_after: self.search_after,
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request/aggregation_type.rs b/rust/cloud-storage/opensearch_query_builder/src/request/aggregation_type.rs
new file mode 100644
index 0000000000..b04bf8a420
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request/aggregation_type.rs
@@ -0,0 +1,114 @@
+use std::borrow::Cow;
+use std::collections::HashMap;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::ToOpenSearchJson;
+
+/// Cardinality Aggregation
+#[derive(Debug, Clone, Serialize)]
+pub struct CardinalityAggregation<'a> {
+ /// The field to aggregate
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+}
+
+impl<'a> CardinalityAggregation<'a> {
+ /// Create a new CardinalityAggregation
+ pub fn new(field: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ }
+ }
+}
+
+impl<'a> ToOpenSearchJson for CardinalityAggregation<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ let mut cardinality_obj = Map::new();
+ cardinality_obj.insert("field".to_string(), Value::String(self.field.to_string()));
+ result.insert("cardinality".to_string(), Value::Object(cardinality_obj));
+ Value::Object(result)
+ }
+}
+
+/// Terms Aggregation
+#[derive(Debug, Clone, Serialize)]
+pub struct TermsAggregation<'a> {
+ /// The field to aggregate
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// The maximum number of terms to return
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub size: Option<u32>,
+ /// Sub-aggregations
+ #[serde(skip_serializing_if = "HashMap::is_empty", default)]
+ pub sub_aggs: HashMap<Cow<'a, str>, AggregationType<'a>>,
+}
+
+impl<'a> TermsAggregation<'a> {
+ /// Create a new TermsAggregation
+ pub fn new(field: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ size: None,
+ sub_aggs: HashMap::new(),
+ }
+ }
+
+ /// Set the maximum number of terms to return
+ pub fn size(mut self, size: u32) -> Self {
+ self.size = Some(size);
+ self
+ }
+
+ /// Add a sub-aggregation
+ pub fn sub_agg(mut self, name: impl Into<Cow<'a, str>>, agg: AggregationType<'a>) -> Self {
+ self.sub_aggs.insert(name.into(), agg);
+ self
+ }
+}
+
+impl<'a> ToOpenSearchJson for TermsAggregation<'a> {
+ fn to_json(&self) -> Value {
+ let mut terms_obj = Map::new();
+ terms_obj.insert("field".to_string(), Value::String(self.field.to_string()));
+
+ if let Some(size) = self.size {
+ terms_obj.insert("size".to_string(), Value::Number(size.into()));
+ }
+
+ let mut result = Map::new();
+ result.insert("terms".to_string(), Value::Object(terms_obj));
+
+ if !self.sub_aggs.is_empty() {
+ let mut aggs_obj = Map::new();
+ for (name, agg) in &self.sub_aggs {
+ aggs_obj.insert(name.to_string(), agg.to_json());
+ }
+ result.insert("aggs".to_string(), Value::Object(aggs_obj));
+ }
+
+ Value::Object(result)
+ }
+}
+
+/// Aggregation Type
+#[derive(Debug, Clone, Serialize)]
+#[serde(tag = "type", content = "params")]
+pub enum AggregationType<'a> {
+ /// Terms aggregation
+ Terms(TermsAggregation<'a>),
+ /// Cardinality aggregation
+ Cardinality(CardinalityAggregation<'a>),
+}
+
+impl<'a> ToOpenSearchJson for AggregationType<'a> {
+ fn to_json(&self) -> Value {
+ match self {
+ AggregationType::Terms(terms) => terms.to_json(),
+ AggregationType::Cardinality(cardinality) => cardinality.to_json(),
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request/collapse.rs b/rust/cloud-storage/opensearch_query_builder/src/request/collapse.rs
new file mode 100644
index 0000000000..aabb6d5afe
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request/collapse.rs
@@ -0,0 +1,31 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::ToOpenSearchJson;
+
+/// Collapse
+#[derive(Debug, Clone, Serialize)]
+pub struct Collapse<'a> {
+ /// The field to collapse on
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+}
+
+impl<'a> Collapse<'a> {
+ /// Create a new Collapse
+ pub fn new(field: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ field: field.into(),
+ }
+ }
+}
+
+impl<'a> ToOpenSearchJson for Collapse<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ result.insert("field".to_string(), Value::String(self.field.to_string()));
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request/highlight.rs b/rust/cloud-storage/opensearch_query_builder/src/request/highlight.rs
new file mode 100644
index 0000000000..3a99fedc97
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request/highlight.rs
@@ -0,0 +1,172 @@
+use std::borrow::Cow;
+use std::collections::HashMap;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::ToOpenSearchJson;
+use crate::util::is_empty_slice;
+
+/// Highlight
+#[derive(Default, Debug, Clone, Serialize)]
+pub struct Highlight<'a> {
+ /// Fields to highlight
+ #[serde(skip_serializing_if = "HashMap::is_empty", default)]
+ pub fields: HashMap<Cow<'a, str>, HighlightField<'a>>,
+ /// Require field match
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub require_field_match: Option<bool>,
+}
+
+impl<'a> Highlight<'a> {
+ /// Create a new Highlight
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Add a field to highlight
+ pub fn field(
+ mut self,
+ field_name: impl Into<Cow<'a, str>>,
+ highlight_field: HighlightField<'a>,
+ ) -> Self {
+ self.fields.insert(field_name.into(), highlight_field);
+ self
+ }
+
+ /// Set whether to require field match
+ pub fn require_field_match(mut self, require_field_match: bool) -> Self {
+ self.require_field_match = Some(require_field_match);
+ self
+ }
+}
+
+impl<'a> ToOpenSearchJson for Highlight<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+
+ if !self.fields.is_empty() {
+ let mut fields_obj = Map::new();
+ for (name, field) in &self.fields {
+ fields_obj.insert(name.to_string(), field.to_json());
+ }
+ result.insert("fields".to_string(), Value::Object(fields_obj));
+ }
+
+ if let Some(require_field_match) = self.require_field_match {
+ result.insert(
+ "require_field_match".to_string(),
+ Value::Bool(require_field_match),
+ );
+ }
+
+ Value::Object(result)
+ }
+}
+
+/// HighlightField
+#[derive(Debug, Clone, Serialize)]
+pub struct HighlightField<'a> {
+ /// Highlight type
+ #[serde(skip_serializing_if = "Option::is_none", rename = "type")]
+ pub highlight_type: Option<Cow<'a, str>>,
+ /// Number of fragments
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub number_of_fragments: Option<u32>,
+ /// Pre-tags
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub pre_tags: Cow<'a, [Cow<'a, str>]>,
+ /// Post-tags
+ #[serde(skip_serializing_if = "is_empty_slice", default, borrow)]
+ pub post_tags: Cow<'a, [Cow<'a, str>]>,
+}
+
+impl<'a> Default for HighlightField<'a> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl<'a> HighlightField<'a> {
+ /// Create a new HighlightField
+ pub fn new() -> Self {
+ Self {
+ highlight_type: None,
+ number_of_fragments: None,
+ pre_tags: Cow::Borrowed(&[]),
+ post_tags: Cow::Borrowed(&[]),
+ }
+ }
+
+ /// Set the highlight type
+ pub fn highlight_type(mut self, highlight_type: impl Into<Cow<'a, str>>) -> Self {
+ self.highlight_type = Some(highlight_type.into());
+ self
+ }
+
+ /// Set the number of fragments
+ pub fn number_of_fragments(mut self, number_of_fragments: u32) -> Self {
+ self.number_of_fragments = Some(number_of_fragments);
+ self
+ }
+
+ /// Add pre-tags
+ pub fn pre_tags<I, S>(mut self, pre_tags: I) -> Self
+ where
+ I: IntoIterator<Item = S>,
+ S: Into<Cow<'a, str>>,
+ {
+ self.pre_tags = pre_tags.into_iter().map(|s| s.into()).collect();
+ self
+ }
+
+ /// Add post-tags
+ pub fn post_tags<I, S>(mut self, post_tags: I) -> Self
+ where
+ I: IntoIterator<Item = S>,
+ S: Into<Cow<'a, str>>,
+ {
+ self.post_tags = post_tags.into_iter().map(|s| s.into()).collect();
+ self
+ }
+}
+
+impl<'a> ToOpenSearchJson for HighlightField<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+
+ if let Some(ref highlight_type) = self.highlight_type {
+ result.insert(
+ "type".to_string(),
+ Value::String(highlight_type.to_string()),
+ );
+ }
+
+ if let Some(number_of_fragments) = self.number_of_fragments {
+ result.insert(
+ "number_of_fragments".to_string(),
+ Value::Number(number_of_fragments.into()),
+ );
+ }
+
+ if !self.pre_tags.is_empty() {
+ let pre_tags: Vec<Value> = self
+ .pre_tags
+ .iter()
+ .map(|tag| Value::String(tag.to_string()))
+ .collect();
+ result.insert("pre_tags".to_string(), Value::Array(pre_tags));
+ }
+
+ if !self.post_tags.is_empty() {
+ let post_tags: Vec<Value> = self
+ .post_tags
+ .iter()
+ .map(|tag| Value::String(tag.to_string()))
+ .collect();
+ result.insert("post_tags".to_string(), Value::Array(post_tags));
+ }
+
+ Value::Object(result)
+ }
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request/sort_type.rs b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type.rs
new file mode 100644
index 0000000000..fc82a916ef
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type.rs
@@ -0,0 +1,175 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::ToOpenSearchJson;
+
+mod script;
+
+pub use script::*;
+
+/// Sort Order
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SortOrder {
+ /// Ascending
+ Asc,
+ /// Descending
+ Desc,
+}
+
+/// Sort Mode
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SortMode {
+ /// Minimum
+ Min,
+ /// Maximum
+ Max,
+ /// Sum
+ Sum,
+ /// Average
+ Avg,
+ /// Median
+ Median,
+}
+
+/// Field Sort
+#[derive(Debug, Clone, Serialize)]
+pub struct FieldSort<'a> {
+ /// The field to sort on
+ #[serde(borrow)]
+ pub field: Cow<'a, str>,
+ /// Sort order
+ pub order: SortOrder,
+ /// Missing value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(borrow)]
+ pub missing: Option<Cow<'a, str>>,
+ /// Unmapped type
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(borrow)]
+ pub unmapped_type: Option<Cow<'a, str>>,
+}
+
+/// Score sort with order
+#[derive(Debug, Clone, Serialize)]
+pub struct ScoreWithOrderSort {
+ /// Sort order
+ pub order: SortOrder,
+}
+
+impl<'a> FieldSort<'a> {
+ /// Create a new FieldSort
+ pub fn new(field: impl Into<Cow<'a, str>>, order: SortOrder) -> Self {
+ Self {
+ field: field.into(),
+ order,
+ missing: None,
+ unmapped_type: None,
+ }
+ }
+
+ /// Set the missing value
+ pub fn missing(mut self, missing: impl Into<Cow<'a, str>>) -> Self {
+ self.missing = Some(missing.into());
+ self
+ }
+
+ /// Set the unmapped type
+ pub fn unmapped_type(mut self, unmapped_type: impl Into<Cow<'a, str>>) -> Self {
+ self.unmapped_type = Some(unmapped_type.into());
+ self
+ }
+}
+
+impl ScoreWithOrderSort {
+ /// Create a new ScoreWithOrderSort
+ pub fn new(order: SortOrder) -> Self {
+ Self { order }
+ }
+}
+
+impl<'a> ToOpenSearchJson for FieldSort<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+
+ // Use simplified format when there are no additional parameters
+ if self.missing.is_none() && self.unmapped_type.is_none() {
+ result.insert(
+ self.field.to_string(),
+ Value::String(match self.order {
+ SortOrder::Asc => "asc".to_string(),
+ SortOrder::Desc => "desc".to_string(),
+ }),
+ );
+ } else {
+ // Use object format when there are additional parameters
+ let mut field_obj = Map::new();
+ field_obj.insert(
+ "order".to_string(),
+ Value::String(match self.order {
+ SortOrder::Asc => "asc".to_string(),
+ SortOrder::Desc => "desc".to_string(),
+ }),
+ );
+
+ if let Some(ref missing) = self.missing {
+ field_obj.insert("missing".to_string(), Value::String(missing.to_string()));
+ }
+
+ if let Some(ref unmapped_type) = self.unmapped_type {
+ field_obj.insert(
+ "unmapped_type".to_string(),
+ Value::String(unmapped_type.to_string()),
+ );
+ }
+
+ result.insert(self.field.to_string(), Value::Object(field_obj));
+ }
+
+ Value::Object(result)
+ }
+}
+
+impl ToOpenSearchJson for ScoreWithOrderSort {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ result.insert(
+ "_score".to_string(),
+ Value::String(match self.order {
+ SortOrder::Asc => "asc".to_string(),
+ SortOrder::Desc => "desc".to_string(),
+ }),
+ );
+ Value::Object(result)
+ }
+}
+
+/// Sort Type
+#[derive(Debug, Clone, Serialize)]
+#[serde(tag = "type", content = "params")]
+pub enum SortType<'a> {
+ /// Field sort
+ Field(FieldSort<'a>),
+ /// Score sort
+ Score,
+ /// Score with sort order
+ ScoreWithOrder(ScoreWithOrderSort),
+ /// Script sort
+ ScriptSort(ScriptSort<'a>),
+}
+impl<'a> ToOpenSearchJson for SortType<'a> {
+ fn to_json(&self) -> Value {
+ match self {
+ SortType::Field(field_sort) => field_sort.to_json(),
+ SortType::Score => serde_json::json!("_score"),
+ SortType::ScoreWithOrder(score_sort) => score_sort.to_json(),
+ SortType::ScriptSort(script_sort) => script_sort.to_json(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/script.rs b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/script.rs
new file mode 100644
index 0000000000..0ff96622e9
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/script.rs
@@ -0,0 +1,146 @@
+use std::borrow::Cow;
+
+use serde::Serialize;
+use serde_json::{Map, Value};
+
+use crate::{SortMode, SortOrder, ToOpenSearchJson};
+
+/// Script Sort Type
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ScriptSortType {
+ /// Number - for numeric values (long, double, float, int)
+ Number,
+ /// String - for string/text values (lexicographic sorting)
+ String,
+ /// Version - for version strings (e.g., "1.2.3")
+ Version,
+}
+
+/// Script Lang
+#[derive(Debug, Clone, Serialize, Default)]
+#[serde(rename_all = "lowercase")]
+pub enum Lang {
+ /// Default and recommended scripting language (Java-like syntax)
+ #[default]
+ Painless,
+ /// Fast, lightweight expressions (limited functionality, numeric operations only)
+ Expression,
+ /// Template language (mainly for search templates, not for sort scripts)
+ Mustache,
+}
+
+/// Script
+#[derive(Debug, Clone, Serialize, Default)]
+pub struct Script<'a> {
+ /// The script
+ pub source: Cow<'a, str>,
+ /// The lang to use (defaults to painless)
+ pub lang: Lang,
+ /// The params to inject into the source
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub params: Option<serde_json::Value>,
+}
+
+impl<'a> Script<'a> {
+ /// Create a new Script with the given source
+ pub fn new(source: impl Into<Cow<'a, str>>) -> Self {
+ Self {
+ source: source.into(),
+ lang: Lang::default(),
+ params: None,
+ }
+ }
+
+ /// Set the script language
+ pub fn lang(mut self, lang: Lang) -> Self {
+ self.lang = lang;
+ self
+ }
+
+ /// Set the script parameters
+ pub fn params(mut self, params: serde_json::Value) -> Self {
+ self.params = Some(params);
+ self
+ }
+}
+
+/// Script Sort
+#[derive(Debug, Clone, Serialize)]
+pub struct ScriptSort<'a> {
+ /// The type of the script sort
+ #[serde(rename = "type")]
+ pub sort_type: ScriptSortType,
+ /// The script
+ pub script: Script<'a>,
+ /// The sort order
+ pub order: SortOrder,
+ /// The mode for the script
+ /// Only relevant for multi-value scripts
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mode: Option<SortMode>,
+}
+
+impl<'a> ScriptSort<'a> {
+ /// Create a new ScriptSort with the given script, type, and order
+ pub fn new(script: Script<'a>, sort_type: ScriptSortType, order: SortOrder) -> Self {
+ Self {
+ sort_type,
+ script,
+ order,
+ mode: None,
+ }
+ }
+
+ /// Set the sort mode
+ pub fn mode(mut self, mode: SortMode) -> Self {
+ self.mode = Some(mode);
+ self
+ }
+}
+
+impl<'a> ToOpenSearchJson for ScriptSort<'a> {
+ fn to_json(&self) -> Value {
+ let mut result = Map::new();
+ let mut script_obj = Map::new();
+
+ // Add type
+ script_obj.insert(
+ "type".to_string(),
+ Value::String(match self.sort_type {
+ ScriptSortType::Number => "number".to_string(),
+ ScriptSortType::String => "string".to_string(),
+ ScriptSortType::Version => "version".to_string(),
+ }),
+ );
+
+ // Add script
+ script_obj.insert(
+ "script".to_string(),
+ serde_json::to_value(&self.script).expect("Failed to serialize script"),
+ );
+
+ // Add order
+ script_obj.insert(
+ "order".to_string(),
+ Value::String(match self.order {
+ SortOrder::Asc => "asc".to_string(),
+ SortOrder::Desc => "desc".to_string(),
+ }),
+ );
+
+ // Add mode if present
+ if let Some(ref mode) = self.mode {
+ script_obj.insert(
+ "mode".to_string(),
+ serde_json::to_value(mode).expect("Failed to serialize mode"),
+ );
+ }
+
+ result.insert("_script".to_string(), Value::Object(script_obj));
+ Value::Object(result)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/script/test.rs b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/script/test.rs
new file mode 100644
index 0000000000..45f1d94585
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/script/test.rs
@@ -0,0 +1,603 @@
+use super::*;
+use crate::ToOpenSearchJson;
+
+#[test]
+fn test_script_sort_basic_number() {
+ // Basic script sort with number type
+ let script = Script {
+ source: "doc['field_name'].value * params.factor".into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script,
+ order: SortOrder::Desc,
+ mode: None,
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['field_name'].value * params.factor",
+ "lang": "painless"
+ },
+ "order": "desc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_with_params() {
+ // Script sort with parameters
+ let script = Script {
+ source: "doc['field_name'].value * params.factor".into(),
+ lang: Lang::Painless,
+ params: Some(serde_json::json!({"factor": 1.5})),
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script,
+ order: SortOrder::Asc,
+ mode: None,
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['field_name'].value * params.factor",
+ "lang": "painless",
+ "params": {
+ "factor": 1.5
+ }
+ },
+ "order": "asc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_string_type() {
+ // Script sort with string type
+ let script = Script {
+ source: "doc['last_name'].value + ', ' + doc['first_name'].value".into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::String,
+ script,
+ order: SortOrder::Asc,
+ mode: None,
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "string",
+ "script": {
+ "source": "doc['last_name'].value + ', ' + doc['first_name'].value",
+ "lang": "painless"
+ },
+ "order": "asc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_version_type() {
+ // Script sort with version type
+ let script = Script {
+ source: "doc['version'].value".into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Version,
+ script,
+ order: SortOrder::Desc,
+ mode: None,
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "version",
+ "script": {
+ "source": "doc['version'].value",
+ "lang": "painless"
+ },
+ "order": "desc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_with_mode_min() {
+ // Script sort with mode set to minimum
+ let script = Script {
+ source: "doc['ratings'].value".into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script,
+ order: SortOrder::Asc,
+ mode: Some(SortMode::Min),
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['ratings'].value",
+ "lang": "painless"
+ },
+ "order": "asc",
+ "mode": "min"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_with_mode_max() {
+ // Script sort with mode set to maximum
+ let script = Script {
+ source: "doc['scores'].value".into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script,
+ order: SortOrder::Desc,
+ mode: Some(SortMode::Max),
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['scores'].value",
+ "lang": "painless"
+ },
+ "order": "desc",
+ "mode": "max"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_with_mode_avg() {
+ // Script sort with mode set to average
+ let script = Script {
+ source: "doc['values'].value".into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script,
+ order: SortOrder::Asc,
+ mode: Some(SortMode::Avg),
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['values'].value",
+ "lang": "painless"
+ },
+ "order": "asc",
+ "mode": "avg"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_with_expression_lang() {
+ // Script sort using expression language
+ let script = Script {
+ source: "doc['price'].value * 1.2".into(),
+ lang: Lang::Expression,
+ params: None,
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script,
+ order: SortOrder::Asc,
+ mode: None,
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['price'].value * 1.2",
+ "lang": "expression"
+ },
+ "order": "asc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_complex_with_all_options() {
+ // Complex script sort with all options set
+ let script = Script {
+ source: "Math.log(doc['value'].value) * params.multiplier".into(),
+ lang: Lang::Painless,
+ params: Some(serde_json::json!({
+ "multiplier": 2.5,
+ "offset": 10
+ })),
+ };
+ let sort = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script,
+ order: SortOrder::Desc,
+ mode: Some(SortMode::Sum),
+ };
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "Math.log(doc['value'].value) * params.multiplier",
+ "lang": "painless",
+ "params": {
+ "multiplier": 2.5,
+ "offset": 10
+ }
+ },
+ "order": "desc",
+ "mode": "sum"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_with_cow_str() {
+ // Test that Cow<str> works correctly with both borrowed and owned strings
+ let borrowed_script = Script {
+ source: "doc['field'].value".into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+ let owned_script = Script {
+ source: "doc['field'].value".to_string().into(),
+ lang: Lang::Painless,
+ params: None,
+ };
+
+ let sort1 = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script: borrowed_script,
+ order: SortOrder::Asc,
+ mode: None,
+ };
+
+ let sort2 = ScriptSort {
+ sort_type: ScriptSortType::Number,
+ script: owned_script,
+ order: SortOrder::Asc,
+ mode: None,
+ };
+
+ let result1 = sort1.to_json();
+ let result2 = sort2.to_json();
+
+ assert_eq!(result1, result2);
+ assert_eq!(
+ result1,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['field'].value",
+ "lang": "painless"
+ },
+ "order": "asc"
+ }
+ })
+ );
+}
+
+// Builder pattern tests
+
+#[test]
+fn test_script_builder_basic() {
+ // Test basic Script::new() builder
+ let script = Script::new("doc['field'].value");
+
+ assert_eq!(script.source, "doc['field'].value");
+ assert!(matches!(script.lang, Lang::Painless));
+ assert!(script.params.is_none());
+}
+
+#[test]
+fn test_script_builder_with_lang() {
+ // Test Script builder with lang
+ let script = Script::new("doc['price'].value * 1.2").lang(Lang::Expression);
+
+ let sort = ScriptSort::new(script, ScriptSortType::Number, SortOrder::Asc);
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['price'].value * 1.2",
+ "lang": "expression"
+ },
+ "order": "asc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_builder_with_params() {
+ // Test Script builder with params
+ let script = Script::new("doc['field'].value * params.factor")
+ .params(serde_json::json!({"factor": 1.5}));
+
+ let sort = ScriptSort::new(script, ScriptSortType::Number, SortOrder::Desc);
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['field'].value * params.factor",
+ "lang": "painless",
+ "params": {
+ "factor": 1.5
+ }
+ },
+ "order": "desc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_builder_chained() {
+ // Test Script builder with all methods chained
+ let script = Script::new("doc['value'].value * params.multiplier")
+ .lang(Lang::Painless)
+ .params(serde_json::json!({
+ "multiplier": 2.0,
+ "threshold": 100
+ }));
+
+ let sort = ScriptSort::new(script, ScriptSortType::Number, SortOrder::Asc);
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['value'].value * params.multiplier",
+ "lang": "painless",
+ "params": {
+ "multiplier": 2.0,
+ "threshold": 100
+ }
+ },
+ "order": "asc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_builder_basic() {
+ // Test basic ScriptSort::new() builder
+ let script = Script::new("doc['ratings'].value");
+ let sort = ScriptSort::new(script, ScriptSortType::Number, SortOrder::Desc);
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['ratings'].value",
+ "lang": "painless"
+ },
+ "order": "desc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_builder_with_mode() {
+ // Test ScriptSort builder with mode
+ let script = Script::new("doc['scores'].value");
+ let sort = ScriptSort::new(script, ScriptSortType::Number, SortOrder::Asc).mode(SortMode::Avg);
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['scores'].value",
+ "lang": "painless"
+ },
+ "order": "asc",
+ "mode": "avg"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_builder_string_type() {
+ // Test ScriptSort builder with string type
+ let script = Script::new("doc['last_name'].value + ', ' + doc['first_name'].value");
+ let sort = ScriptSort::new(script, ScriptSortType::String, SortOrder::Asc);
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "string",
+ "script": {
+ "source": "doc['last_name'].value + ', ' + doc['first_name'].value",
+ "lang": "painless"
+ },
+ "order": "asc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_builder_version_type() {
+ // Test ScriptSort builder with version type
+ let script = Script::new("doc['version'].value");
+ let sort = ScriptSort::new(script, ScriptSortType::Version, SortOrder::Desc);
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "version",
+ "script": {
+ "source": "doc['version'].value",
+ "lang": "painless"
+ },
+ "order": "desc"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_builder_fully_chained() {
+ // Test fully chained builder pattern
+ let sort = ScriptSort::new(
+ Script::new("Math.log(doc['value'].value) * params.multiplier")
+ .lang(Lang::Painless)
+ .params(serde_json::json!({
+ "multiplier": 2.5,
+ "offset": 10
+ })),
+ ScriptSortType::Number,
+ SortOrder::Desc,
+ )
+ .mode(SortMode::Sum);
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "Math.log(doc['value'].value) * params.multiplier",
+ "lang": "painless",
+ "params": {
+ "multiplier": 2.5,
+ "offset": 10
+ }
+ },
+ "order": "desc",
+ "mode": "sum"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_script_sort_builder_with_expression_and_mode() {
+ // Test builder with expression language and mode
+ let sort = ScriptSort::new(
+ Script::new("doc['price'].value * 1.19").lang(Lang::Expression),
+ ScriptSortType::Number,
+ SortOrder::Asc,
+ )
+ .mode(SortMode::Max);
+
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_script": {
+ "type": "number",
+ "script": {
+ "source": "doc['price'].value * 1.19",
+ "lang": "expression"
+ },
+ "order": "asc",
+ "mode": "max"
+ }
+ })
+ );
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/test.rs b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/test.rs
new file mode 100644
index 0000000000..6c4c4a59cb
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/request/sort_type/test.rs
@@ -0,0 +1,150 @@
+use super::*;
+use crate::ToOpenSearchJson;
+
+#[test]
+fn test_field_sort_simplified_format() {
+ // When neither missing nor unmapped_type is set, should use simplified format
+ let sort = FieldSort::new("timestamp", SortOrder::Desc);
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "timestamp": "desc"
+ })
+ );
+}
+
+#[test]
+fn test_field_sort_with_missing() {
+ // When only missing is set, should use object format
+ let sort = FieldSort::new("price", SortOrder::Asc).missing("_last");
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "price": {
+ "order": "asc",
+ "missing": "_last"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_field_sort_with_unmapped_type() {
+ // When only unmapped_type is set, should use object format
+ let sort = FieldSort::new("user_count", SortOrder::Desc).unmapped_type("long");
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "user_count": {
+ "order": "desc",
+ "unmapped_type": "long"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_field_sort_with_both_parameters() {
+ // When both missing and unmapped_type are set, should include both
+ let sort = FieldSort::new("score", SortOrder::Asc)
+ .missing("_first")
+ .unmapped_type("double");
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "score": {
+ "order": "asc",
+ "missing": "_first",
+ "unmapped_type": "double"
+ }
+ })
+ );
+}
+
+#[test]
+fn test_score_sort() {
+ // Basic score sort
+ let sort = SortType::Score;
+ let result = sort.to_json();
+
+ assert_eq!(result, serde_json::json!("_score"));
+}
+
+#[test]
+fn test_score_with_order_asc() {
+ // Score sort with ascending order
+ let sort = ScoreWithOrderSort::new(SortOrder::Asc);
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_score": "asc"
+ })
+ );
+}
+
+#[test]
+fn test_score_with_order_desc() {
+ // Score sort with descending order
+ let sort = ScoreWithOrderSort::new(SortOrder::Desc);
+ let result = sort.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_score": "desc"
+ })
+ );
+}
+
+#[test]
+fn test_sort_type_field_variant() {
+ // Test SortType enum with Field variant
+ let field_sort = FieldSort::new("category", SortOrder::Asc);
+ let sort_type = SortType::Field(field_sort);
+ let result = sort_type.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "category": "asc"
+ })
+ );
+}
+
+#[test]
+fn test_sort_type_score_with_order_variant() {
+ // Test SortType enum with ScoreWithOrder variant
+ let score_sort = ScoreWithOrderSort::new(SortOrder::Desc);
+ let sort_type = SortType::ScoreWithOrder(score_sort);
+ let result = sort_type.to_json();
+
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "_score": "desc"
+ })
+ );
+}
+
+#[test]
+fn test_field_sort_with_cow_str() {
+ // Test that Cow<str> works correctly with both borrowed and owned strings
+ let borrowed_sort = FieldSort::new("field1", SortOrder::Asc);
+ let owned_sort = FieldSort::new("field2".to_string(), SortOrder::Desc);
+
+ let result1 = borrowed_sort.to_json();
+ let result2 = owned_sort.to_json();
+
+ assert_eq!(result1, serde_json::json!({"field1": "asc"}));
+ assert_eq!(result2, serde_json::json!({"field2": "desc"}));
+}
diff --git a/rust/cloud-storage/opensearch_query_builder/src/util.rs b/rust/cloud-storage/opensearch_query_builder/src/util.rs
new file mode 100644
index 0000000000..f9d160c783
--- /dev/null
+++ b/rust/cloud-storage/opensearch_query_builder/src/util.rs
@@ -0,0 +1,6 @@
+//! This module contains utility functions that are used within this crate.
+
+/// Serialization skip condition for empty slices.
+pub fn is_empty_slice<T: Clone>(slice: &[T]) -> bool {
+ slice.is_empty()
+}