meilisearch-sdk 0.33.0

Rust wrapper for the Meilisearch API. Meilisearch is a powerful, fast, open-source, easy to use and deploy search engine.
Documentation
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crate::{
    errors::Error,
    indexes::Index,
    request::HttpClient,
    search::{Filter, Selectors},
};
use either::Either;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{Map, Value};

#[derive(Deserialize, Debug, Clone)]
pub struct SimilarResult<T> {
    #[serde(flatten)]
    pub result: T,
    #[serde(rename = "_rankingScore")]
    pub ranking_score: Option<f64>,
    #[serde(rename = "_rankingScoreDetails")]
    pub ranking_score_details: Option<Map<String, Value>>,
}

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SimilarResults<T> {
    /// Results of the query
    pub hits: Vec<SimilarResult<T>>,
    /// Number of documents skipped
    pub offset: Option<usize>,
    /// Number of results returned
    pub limit: Option<usize>,
    /// Estimated total number of matches
    pub estimated_total_hits: Option<usize>,
    /// Performance trace of the query
    pub performance_details: Option<Value>,
    /// Processing time of the query
    pub processing_time_ms: usize,
    /// Identifier of the target document
    pub id: String,
}

/// A struct representing a query.
///
/// You can add similar parameters using the builder syntax.
///
/// See [this page](https://www.meilisearch.com/docs/reference/api/similar#get-similar-documents-with-post) for the official list and description of all parameters.
///
/// # Examples
///
/// ```no_run
/// # use serde::{Serialize, Deserialize};
/// # use meilisearch_sdk::{client::Client, search::*, indexes::Index};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # #[derive(Serialize, Deserialize, Debug)]
/// # struct Movie {
/// #    name: String,
/// #    description: String,
/// # }
/// #
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// # let index = client.index("similar_query_builder");
/// #
/// let mut res = index.similar_search("100", "default")
///     .execute::<Movie>()
///     .await
///     .unwrap();
/// #
/// # index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
/// ```
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SimilarQuery<'a, Http: HttpClient> {
    #[serde(skip_serializing)]
    index: &'a Index<Http>,

    /// Identifier of the target document
    pub id: &'a str,

    /// Embedder to use when computing recommendations
    pub embedder: &'a str,

    /// Number of documents to skip
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<usize>,

    /// Maximum number of documents returned
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,

    /// Filter queries by an attribute’s value
    ///
    /// Read the [dedicated guide](https://www.meilisearch.com/docs/learn/filtering_and_sorting) to learn the syntax.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter: Option<Filter<'a>>,

    /// Attributes to display in the returned documents.
    ///
    /// Can be set to a [wildcard value](enum.Selectors.html#variant.All) that will select all existing attributes.
    ///
    /// **Default: all attributes found in the documents.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes_to_retrieve: Option<Selectors<&'a [&'a str]>>,

    /// Defines whether to display the global ranking score of a document
    ///
    /// **Default: `false`**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub show_ranking_score: Option<bool>,

    /// Defines whether to display the detailed ranking score information
    ///
    /// **Default: `false`**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub show_ranking_score_details: Option<bool>,

    /// Defines whether to exclude results with low ranking scores
    ///
    /// **Default: `None`**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ranking_score_threshold: Option<f64>,

    /// Defines whether to return document vector data
    ///
    /// **Default: `false`**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retrieve_vectors: Option<bool>,

    /// Defines whether to return performance trace
    ///
    /// **Default: `false`**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub show_performance_details: Option<bool>,
}

#[allow(missing_docs)]
impl<'a, Http: HttpClient> SimilarQuery<'a, Http> {
    #[must_use]
    pub fn new(index: &'a Index<Http>, id: &'a str, embedder: &'a str) -> SimilarQuery<'a, Http> {
        SimilarQuery {
            index,
            id,
            embedder,
            offset: None,
            limit: None,
            filter: None,
            attributes_to_retrieve: None,
            show_ranking_score: None,
            show_ranking_score_details: None,
            ranking_score_threshold: None,
            retrieve_vectors: None,
            show_performance_details: None,
        }
    }

    pub fn with_offset<'b>(&'b mut self, offset: usize) -> &'b mut SimilarQuery<'a, Http> {
        self.offset = Some(offset);
        self
    }

    pub fn with_limit<'b>(&'b mut self, limit: usize) -> &'b mut SimilarQuery<'a, Http> {
        self.limit = Some(limit);
        self
    }

    pub fn with_filter<'b>(&'b mut self, filter: &'a str) -> &'b mut SimilarQuery<'a, Http> {
        self.filter = Some(Filter::new(Either::Left(filter)));
        self
    }

    pub fn with_array_filter<'b>(
        &'b mut self,
        filter: Vec<&'a str>,
    ) -> &'b mut SimilarQuery<'a, Http> {
        self.filter = Some(Filter::new(Either::Right(filter)));
        self
    }

    pub fn with_attributes_to_retrieve<'b>(
        &'b mut self,
        attributes_to_retrieve: Selectors<&'a [&'a str]>,
    ) -> &'b mut SimilarQuery<'a, Http> {
        self.attributes_to_retrieve = Some(attributes_to_retrieve);
        self
    }

    pub fn with_show_ranking_score<'b>(
        &'b mut self,
        show_ranking_score: bool,
    ) -> &'b mut SimilarQuery<'a, Http> {
        self.show_ranking_score = Some(show_ranking_score);
        self
    }

    pub fn with_show_ranking_score_details<'b>(
        &'b mut self,
        show_ranking_score_details: bool,
    ) -> &'b mut SimilarQuery<'a, Http> {
        self.show_ranking_score_details = Some(show_ranking_score_details);
        self
    }

    pub fn with_ranking_score_threshold<'b>(
        &'b mut self,
        ranking_score_threshold: f64,
    ) -> &'b mut SimilarQuery<'a, Http> {
        self.ranking_score_threshold = Some(ranking_score_threshold);
        self
    }

    pub fn with_retrieve_vectors<'b>(
        &'b mut self,
        retrieve_vectors: bool,
    ) -> &'b mut SimilarQuery<'a, Http> {
        self.retrieve_vectors = Some(retrieve_vectors);
        self
    }

    /// Request performance trace in the response.
    pub fn with_show_performance_details<'b>(
        &'b mut self,
        show_performance_details: bool,
    ) -> &'b mut SimilarQuery<'a, Http> {
        self.show_performance_details = Some(show_performance_details);
        self
    }

    /// Execute the query and fetch the results.
    pub async fn execute<T: 'static + DeserializeOwned + Send + Sync>(
        &'a self,
    ) -> Result<SimilarResults<T>, Error> {
        self.index.execute_similar_query::<T>(self).await
    }
}

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;
    use crate::{
        client::*,
        search::{
            tests::{setup_embedder, setup_test_index, Document},
            *,
        },
    };
    use meilisearch_test_macro::meilisearch_test;

    #[meilisearch_test]
    async fn test_similar_results(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        // Test on a non-harry-potter document
        let mut query = SimilarQuery::new(&index, "0", "default");
        query.with_limit(1);
        let results: SimilarResults<Document> = query.execute().await?;
        let result = results.hits.first().unwrap();
        assert_eq!(result.result.id, 1);

        // Test on a harry-potter document
        let mut query = SimilarQuery::new(&index, "3", "default");
        query.with_limit(1);
        let results: SimilarResults<Document> = query.execute().await?;
        let result = results.hits.first().unwrap();
        assert_eq!(result.result.id, 4);

        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_limit(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_limit(3);

        let results: SimilarResults<Document> = query.execute().await?;
        assert_eq!(results.hits.len(), 3);
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_offset(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_offset(6);

        let results: SimilarResults<Document> = query.execute().await?;
        assert_eq!(results.hits.len(), 3);
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_filter(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");

        let results: SimilarResults<Document> =
            query.with_filter("kind = \"title\"").execute().await?;
        assert_eq!(results.hits.len(), 8);

        let results: SimilarResults<Document> =
            query.with_filter("NOT kind = \"title\"").execute().await?;
        assert_eq!(results.hits.len(), 1);
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_filter_with_array(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        let results: SimilarResults<Document> = query
            .with_array_filter(vec!["kind = \"title\"", "kind = \"text\""])
            .execute()
            .await?;
        assert_eq!(results.hits.len(), 0);

        let mut query = SimilarQuery::new(&index, "1", "default");
        let results: SimilarResults<Document> = query
            .with_array_filter(vec!["kind = \"title\"", "number <= 50"])
            .execute()
            .await?;
        assert_eq!(results.hits.len(), 4);

        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_attributes_to_retrieve(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        let results: SimilarResults<Document> = query
            .with_attributes_to_retrieve(Selectors::All)
            .execute()
            .await?;
        assert_eq!(results.hits.len(), 9);

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_attributes_to_retrieve(Selectors::Some(&["title", "id"])); // omit the "value" field
        assert!(query.execute::<Document>().await.is_err()); // error: missing "value" field
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_show_ranking_score(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_show_ranking_score(true);
        let results: SimilarResults<Document> = query.execute().await?;
        assert!(results.hits[0].ranking_score.is_some());
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_show_ranking_score_details(
        client: Client,
        index: Index,
    ) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_show_ranking_score_details(true);
        let results: SimilarResults<Document> = query.execute().await?;
        assert!(results.hits[0].ranking_score_details.is_some());
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_show_ranking_score_threshold(
        client: Client,
        index: Index,
    ) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_ranking_score_threshold(1.0);
        let results: SimilarResults<Document> = query.execute().await?;
        assert!(results.hits.is_empty());
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_retrieve_vectors(client: Client, index: Index) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_retrieve_vectors(true);
        let results: SimilarResults<Document> = query.execute().await?;
        assert!(results.hits[0].result._vectors.is_some());
        Ok(())
    }

    #[meilisearch_test]
    async fn test_query_show_performance_details(
        client: Client,
        index: Index,
    ) -> Result<(), Error> {
        setup_embedder(&client, &index).await?;
        setup_test_index(&client, &index).await?;

        let mut query = SimilarQuery::new(&index, "1", "default");
        query.with_show_performance_details(true);
        let results: SimilarResults<Document> = query.execute().await?;
        assert!(results.performance_details.is_some());
        Ok(())
    }
}