-
Notifications
You must be signed in to change notification settings - Fork 16
/
mod.rs
281 lines (259 loc) · 10.4 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
//! A k-nearest neighbor (kNN) search finds the k nearest vectors to a query vector, as measured by a similarity metric.
//! Common use cases for kNN include:
//! - Relevance ranking based on natural language processing (NLP) algorithms
//! - Product recommendations and recommendation engines
//! - Similarity search for images or videos
//!
//! <https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#approximate-knn>
use crate::search::*;
use crate::util::*;
use serde::Serialize;
/// Performs a k-nearest neighbor (kNN) search and returns the matching documents.
///
/// The kNN search API performs a k-nearest neighbor (kNN) search on a `dense_vector` field. Given a query vector, it
/// finds the _k_ closest vectors and returns those documents as search hits.
///
/// Elasticsearch uses the HNSW algorithm to support efficient kNN search. Like most kNN algorithms, HNSW is an
/// approximate method that sacrifices result accuracy for improved search speed. This means the results returned are
/// not always the true _k_ closest neighbors.
///
/// The kNN search API supports restricting the search using a filter. The search will return the top `k` documents
/// that also match the filter query.
///
/// To create a knn search with a query vector or query vector builder:
/// ```
/// # use elasticsearch_dsl::*;
/// # let search =
/// Search::new()
/// .knn(Knn::query_vector("test1", vec![1.0, 2.0, 3.0]))
/// .knn(Knn::query_vector_builder("test3", TextEmbedding::new("my-text-embedding-model", "The opposite of pink")));
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-knn-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Knn {
field: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
query_vector: Option<Vec<f32>>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
query_vector_builder: Option<QueryVectorBuilder>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
k: Option<u32>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
num_candidates: Option<u32>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
filter: Option<Box<Query>>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
similarity: Option<f32>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
boost: Option<f32>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
_name: Option<String>,
}
impl Knn {
/// Creates an instance of [`Knn`] search with query vector
///
/// - `field` - The name of the vector field to search against. Must be a dense_vector field with indexing enabled.
/// - `query_vector` - Query vector. Must have the same number of dimensions as the vector field you are searching
/// against.
pub fn query_vector<T>(field: T, query_vector: Vec<f32>) -> Self
where
T: ToString,
{
Self {
field: field.to_string(),
query_vector: Some(query_vector),
query_vector_builder: None,
k: None,
num_candidates: None,
filter: None,
similarity: None,
boost: None,
_name: None,
}
}
/// Creates an instance of [`Knn`] search with query vector builder
///
/// - `field` - The name of the vector field to search against. Must be a dense_vector field with indexing enabled.
/// - `query_vector_builder` - A configuration object indicating how to build a query_vector before executing the request.
pub fn query_vector_builder<T, U>(field: T, query_vector_builder: U) -> Self
where
T: ToString,
U: Into<QueryVectorBuilder>,
{
Self {
field: field.to_string(),
query_vector: None,
query_vector_builder: Some(query_vector_builder.into()),
k: None,
num_candidates: None,
filter: None,
similarity: None,
boost: None,
_name: None,
}
}
/// Number of nearest neighbors to return as top hits. This value must be less than `num_candidates`.
///
/// Defaults to `size`.
pub fn k(mut self, k: u32) -> Self {
self.k = Some(k);
self
}
/// The number of nearest neighbor candidates to consider per shard. Cannot exceed 10,000. Elasticsearch collects
/// `num_candidates` results from each shard, then merges them to find the top results. Increasing `num_candidates`
/// tends to improve the accuracy of the final results. Defaults to `Math.min(1.5 * size, 10_000)`.
pub fn num_candidates(mut self, num_candidates: u32) -> Self {
self.num_candidates = Some(num_candidates);
self
}
/// Query to filter the documents that can match. The kNN search will return the top documents that also match
/// this filter. The value can be a single query or a list of queries. If `filter` is not provided, all documents
/// are allowed to match.
///
/// The filter is a pre-filter, meaning that it is applied **during** the approximate kNN search to ensure that
/// `num_candidates` matching documents are returned.
pub fn filter<T>(mut self, filter: T) -> Self
where
T: Into<Query>,
{
self.filter = Some(Box::new(filter.into()));
self
}
/// The minimum similarity required for a document to be considered a match. The similarity value calculated
/// relates to the raw similarity used. Not the document score. The matched documents are then scored according
/// to similarity and the provided boost is applied.
pub fn similarity(mut self, similarity: f32) -> Self {
self.similarity = Some(similarity);
self
}
add_boost_and_name!();
}
/// A configuration object indicating how to build a query_vector before executing the request.
///
/// Currently, the only supported builder is [`TextEmbedding`].
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/8.13/knn-search.html#knn-semantic-search>
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum QueryVectorBuilder {
/// The natural language processing task to perform.
TextEmbedding(TextEmbedding),
}
/// The natural language processing task to perform.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TextEmbedding {
model_id: String,
model_text: String,
}
impl From<TextEmbedding> for QueryVectorBuilder {
fn from(embedding: TextEmbedding) -> Self {
Self::TextEmbedding(embedding)
}
}
impl TextEmbedding {
/// Creates an instance of [`TextEmbedding`]
/// - `model_id` - The ID of the text embedding model to use to generate the dense vectors from the query string.
/// Use the same model that generated the embeddings from the input text in the index you search against. You can
/// use the value of the deployment_id instead in the model_id argument.
/// - `model_text` - The query string from which the model generates the dense vector representation.
pub fn new<T, U>(model_id: T, model_text: U) -> Self
where
T: ToString,
U: ToString,
{
Self {
model_id: model_id.to_string(),
model_text: model_text.to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialization() {
assert_serialize(
Search::new()
.knn(Knn::query_vector("test1", vec![1.0, 2.0, 3.0]))
.knn(
Knn::query_vector("test2", vec![4.0, 5.0, 6.0])
.k(3)
.num_candidates(100)
.filter(Query::term("field", "value"))
.similarity(0.5)
.boost(2.0)
.name("test2"),
)
.knn(Knn::query_vector_builder(
"test3",
TextEmbedding::new("my-text-embedding-model", "The opposite of pink"),
))
.knn(
Knn::query_vector_builder(
"test4",
TextEmbedding::new("my-text-embedding-model", "The opposite of blue"),
)
.k(5)
.num_candidates(200)
.filter(Query::term("field", "value"))
.similarity(0.7)
.boost(2.1)
.name("test4"),
),
json!({
"knn": [
{
"field": "test1",
"query_vector": [1.0, 2.0, 3.0]
},
{
"field": "test2",
"query_vector": [4.0, 5.0, 6.0],
"k": 3,
"num_candidates": 100,
"filter": {
"term": {
"field": {
"value": "value"
}
}
},
"similarity": 0.5,
"boost": 2.0,
"_name": "test2"
},
{
"field": "test3",
"query_vector_builder": {
"text_embedding": {
"model_id": "my-text-embedding-model",
"model_text": "The opposite of pink"
}
}
},
{
"field": "test4",
"query_vector_builder": {
"text_embedding": {
"model_id": "my-text-embedding-model",
"model_text": "The opposite of blue"
}
},
"k": 5,
"num_candidates": 200,
"filter": {
"term": {
"field": {
"value": "value"
}
}
},
"similarity": 0.7,
"boost": 2.1,
"_name": "test4"
}
]
}),
);
}
}