use serde_json::Value;
use crate::query_dsl::{
BoolQuery, ExistsQuery, IdsQuery, IntervalsMatch, IntervalsQuery, IntervalsQueryVariant,
MatchAllQuery, MatchPhraseQuery, MatchQuery, MatchQueryQuery, MultiMatchQuery, NestedQuery,
QueryContainer, RangeQuery, SemanticQuery, SparseVectorQuery, SparseVectorQueryVariant,
TermQuery, TermsQuery, TermsQueryField,
};
use crate::search::{Rescore, RescoreQuery, RescoreVariant};
use crate::shapes::{IndexMap, SingleKey};
use crate::{
DiversifyRetriever, DiversifyRetrieverTypes, FieldValue, InnerRetriever, KnnQuery,
KnnRetriever, LinearRetriever, PinnedRetriever, RRFRetriever, RRFRetrieverEntry,
RescorerRetriever, RetrieverContainer, RuleRetriever, StandardRetriever,
TextSimilarityReranker,
};
pub struct Query;
impl Query {
pub fn match_all() -> QueryContainer {
MatchAllQuery::new().into()
}
pub fn r#match(field: impl Into<String>, text: impl Into<MatchQueryQuery>) -> QueryContainer {
keyed(field, MatchQuery::new(text)).into()
}
pub fn match_phrase(field: impl Into<String>, text: impl Into<String>) -> QueryContainer {
keyed(field, MatchPhraseQuery::new(text)).into()
}
pub fn multi_match<F: Into<String>>(
fields: impl IntoIterator<Item = F>,
text: impl Into<String>,
) -> QueryContainer {
let fields: Vec<String> = fields.into_iter().map(Into::into).collect();
MultiMatchQuery::new(text).fields(fields).into()
}
pub fn term(field: impl Into<String>, value: impl Into<FieldValue>) -> QueryContainer {
keyed(field, TermQuery::new(value)).into()
}
pub fn terms<V: Into<FieldValue>>(
field: impl Into<String>,
values: impl IntoIterator<Item = V>,
) -> QueryContainer {
let values: Vec<FieldValue> = values.into_iter().map(Into::into).collect();
TermsQuery::new(field, TermsQueryField::Value(values)).into()
}
pub fn range(field: impl Into<String>, range: impl Into<RangeQuery>) -> QueryContainer {
keyed(field, range.into()).into()
}
pub fn exists(field: impl Into<String>) -> QueryContainer {
ExistsQuery::new(field).into()
}
pub fn ids<I: Into<String>>(ids: impl IntoIterator<Item = I>) -> QueryContainer {
let ids: Vec<String> = ids.into_iter().map(Into::into).collect();
IdsQuery::new().values(ids).into()
}
pub fn bool() -> BoolQuery {
BoolQuery::new()
}
pub fn nested(path: impl Into<String>, query: impl Into<QueryContainer>) -> QueryContainer {
NestedQuery::new(path, query).into()
}
pub fn knn(field: impl Into<String>, vector: Vec<f32>, k: i32) -> QueryContainer {
KnnQuery::new(field).query_vector(vector).k(k).into()
}
pub fn semantic(field: impl Into<String>, text: impl Into<String>) -> QueryContainer {
SemanticQuery::new(field, text).into()
}
pub fn sparse_vector<T: Into<String>>(
field: impl Into<String>,
weights: impl IntoIterator<Item = (T, f32)>,
) -> QueryContainer {
let weights: IndexMap<String, f32> =
weights.into_iter().map(|(t, w)| (t.into(), w)).collect();
SparseVectorQuery::new(field)
.variant(SparseVectorQueryVariant::QueryVector(weights))
.into()
}
pub fn sparse_vector_text(
field: impl Into<String>,
inference_id: impl Into<String>,
text: impl Into<String>,
) -> QueryContainer {
SparseVectorQuery::new(field)
.variant(SparseVectorQueryVariant::InferenceId(inference_id.into()))
.query(text)
.into()
}
pub fn intervals(field: impl Into<String>, text: impl Into<String>) -> QueryContainer {
let rule =
IntervalsQuery::new().variant(IntervalsQueryVariant::Match(IntervalsMatch::new(text)));
keyed(field, rule).into()
}
}
fn keyed<V>(field: impl Into<String>, value: V) -> SingleKey<String, V> {
SingleKey::new(field, value)
}
impl From<QueryContainer> for RetrieverContainer {
fn from(query: QueryContainer) -> RetrieverContainer {
Retriever::standard(query)
}
}
pub struct Retriever;
impl Retriever {
pub fn standard(query: impl Into<QueryContainer>) -> RetrieverContainer {
StandardRetriever::new().query(query).into()
}
pub fn knn(
field: impl Into<String>,
vector: Vec<f32>,
k: i32,
num_candidates: i32,
) -> RetrieverContainer {
KnnRetriever::new(field, k)
.query_vector(vector)
.num_candidates(num_candidates)
.into()
}
pub fn rrf<R: Into<RetrieverContainer>>(
retrievers: impl IntoIterator<Item = R>,
) -> RetrieverContainer {
let entries: Vec<RRFRetrieverEntry> = retrievers
.into_iter()
.map(|retriever| retriever.into().into())
.collect();
RRFRetriever::new(entries).into()
}
pub fn linear<R: Into<RetrieverContainer>>(
retrievers: impl IntoIterator<Item = (R, f32)>,
) -> RetrieverContainer {
let inner: Vec<InnerRetriever> = retrievers
.into_iter()
.map(|(retriever, weight)| InnerRetriever::new(retriever.into()).weight(weight))
.collect();
LinearRetriever::new().retrievers(inner).into()
}
pub fn pinned<I: Into<String>>(
retriever: impl Into<RetrieverContainer>,
ids: impl IntoIterator<Item = I>,
) -> RetrieverContainer {
let ids: Vec<String> = ids.into_iter().map(Into::into).collect();
PinnedRetriever::new(retriever.into()).ids(ids).into()
}
pub fn rescorer(
retriever: impl Into<RetrieverContainer>,
query: impl Into<QueryContainer>,
window_size: i32,
) -> RetrieverContainer {
let rescore = Rescore::new()
.window_size(window_size)
.variant(RescoreVariant::Query(RescoreQuery::new(query)));
RescorerRetriever::new(retriever.into(), rescore).into()
}
pub fn rerank(
retriever: impl Into<RetrieverContainer>,
field: impl Into<String>,
text: impl Into<String>,
) -> RetrieverContainer {
TextSimilarityReranker::new(retriever.into(), text, field).into()
}
pub fn rule(
retriever: impl Into<RetrieverContainer>,
ruleset: impl Into<String>,
match_criteria: Value,
) -> RetrieverContainer {
RuleRetriever::new(ruleset.into(), match_criteria, retriever.into()).into()
}
pub fn diversify(
retriever: impl Into<RetrieverContainer>,
field: impl Into<String>,
vector: Vec<f32>,
) -> RetrieverContainer {
DiversifyRetriever::new(DiversifyRetrieverTypes::Mmr, field, retriever.into())
.query_vector(vector)
.into()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn json(value: &impl serde::Serialize) -> Value {
serde_json::to_value(value).unwrap()
}
#[test]
fn queries() {
assert_eq!(
json(&Query::r#match("title", "hnsw")),
json!({"match": {"title": "hnsw"}})
);
assert_eq!(
json(&Query::term("tag", "vector")),
json!({"term": {"tag": "vector"}})
);
assert_eq!(
json(&Query::terms("tag", ["a", "b"])),
json!({"terms": {"tag": ["a", "b"]}})
);
assert_eq!(
json(
&Query::bool()
.must(Query::r#match("title", "hnsw"))
.filter(Query::term("tag", "vector"))
),
json!({"must": {"match": {"title": "hnsw"}}, "filter": {"term": {"tag": "vector"}}})
);
assert_eq!(
json(&Query::sparse_vector("terms", [("hnsw", 1.0)])),
json!({"sparse_vector": {"field": "terms", "query_vector": {"hnsw": 1.0}}})
);
assert_eq!(
json(&Query::intervals("title", "bulk loading")),
json!({"intervals": {"title": {"match": {"query": "bulk loading"}}}})
);
}
#[test]
fn retrievers() {
let hybrid = Retriever::rrf([
Retriever::standard(Query::r#match("title", "hnsw")),
Retriever::knn("embedding", vec![1.0, 0.0], 5, 50),
]);
assert_eq!(
json(&hybrid),
json!({"rrf": {"retrievers": [
{"standard": {"query": {"match": {"title": "hnsw"}}}},
{"knn": {"field": "embedding", "k": 5, "query_vector": [1.0, 0.0], "num_candidates": 50}}
]}})
);
let linear = Retriever::linear([(Query::match_all(), 2.0)]);
assert_eq!(
json(&linear),
json!({"linear": {"retrievers": [{"retriever": {"standard": {"query": {"match_all": {}}}}, "weight": 2.0}]}})
);
}
}