Skip to content

Commit 5943cb7

Browse files
authored
Update document query for v0.28.0 (#326)
* Add a documentQuery structure to handler query parameters on get document * Fix clippy error * Improve comment test * Improve comment test
1 parent ba0bb42 commit 5943cb7

File tree

2 files changed

+146
-18
lines changed

2 files changed

+146
-18
lines changed

src/documents.rs

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,89 @@ pub struct DocumentsResults<T> {
1111

1212
#[derive(Debug, Clone, Serialize)]
1313
pub struct DocumentQuery<'a> {
14+
#[serde(skip_serializing)]
15+
pub index: &'a Index,
16+
1417
/// The fields that should appear in the documents. By default all of the fields are present.
1518
#[serde(skip_serializing_if = "Option::is_none")]
1619
pub fields: Option<Vec<&'a str>>,
1720
}
1821

22+
impl<'a> DocumentQuery<'a> {
23+
pub fn new(index: &Index) -> DocumentQuery {
24+
DocumentQuery {
25+
index,
26+
fields: None,
27+
}
28+
}
29+
30+
/// Specify the fields to return in the document.
31+
///
32+
/// # Example
33+
///
34+
/// ```
35+
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
36+
/// #
37+
/// # let MEILISEARCH_HOST = option_env!("MEILISEARCH_HOST").unwrap_or("http://localhost:7700");
38+
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
39+
/// #
40+
/// # let client = Client::new(MEILISEARCH_HOST, MEILISEARCH_API_KEY);
41+
/// let index = client.index("document_query_with_fields");
42+
/// let mut document_query = DocumentQuery::new(&index);
43+
///
44+
/// document_query.with_fields(["title"]);
45+
/// ```
46+
pub fn with_fields(
47+
&mut self,
48+
fields: impl IntoIterator<Item = &'a str>,
49+
) -> &mut DocumentQuery<'a> {
50+
self.fields = Some(fields.into_iter().collect());
51+
self
52+
}
53+
54+
/// Execute the get document query.
55+
///
56+
/// # Example
57+
///
58+
/// ```
59+
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
60+
/// # use serde::{Deserialize, Serialize};
61+
/// #
62+
/// # let MEILISEARCH_HOST = option_env!("MEILISEARCH_HOST").unwrap_or("http://localhost:7700");
63+
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
64+
/// #
65+
/// # let client = Client::new(MEILISEARCH_HOST, MEILISEARCH_API_KEY);
66+
///
67+
/// # futures::executor::block_on(async move {
68+
/// #[derive(Debug, Serialize, Deserialize, PartialEq)]
69+
/// struct MyObject {
70+
/// id: String,
71+
/// kind: String,
72+
/// }
73+
/// #[derive(Debug, Serialize, Deserialize, PartialEq)]
74+
/// struct MyObjectReduced {
75+
/// id: String,
76+
/// }
77+
///
78+
/// # let index = client.index("document_query_execute");
79+
/// # index.add_or_replace(&[MyObject{id:"1".to_string(), kind:String::from("a kind")},MyObject{id:"2".to_string(), kind:String::from("some kind")}], None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
80+
///
81+
/// let document = DocumentQuery::new(&index).with_fields(["id"]).execute::<MyObjectReduced>("1").await.unwrap();
82+
///
83+
/// assert_eq!(
84+
/// document,
85+
/// MyObjectReduced { id: "1".to_string() }
86+
/// );
87+
/// # index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
88+
/// # });
89+
pub async fn execute<T: DeserializeOwned + 'static>(
90+
&self,
91+
document_id: &str,
92+
) -> Result<T, Error> {
93+
self.index.get_document_with::<T>(document_id, self).await
94+
}
95+
}
96+
1997
#[derive(Debug, Clone, Serialize)]
2098
pub struct DocumentsQuery<'a> {
2199
#[serde(skip_serializing)]
@@ -144,9 +222,13 @@ impl<'a> DocumentsQuery<'a> {
144222
/// }
145223
/// let index = client.index("documents_query_execute");
146224
///
147-
/// let mut documents_query = DocumentsQuery::new(&index);
225+
/// let document = DocumentsQuery::new(&index)
226+
/// .with_offset(1)
227+
/// .execute::<MyObject>()
228+
/// .await
229+
/// .unwrap();
148230
///
149-
/// documents_query.with_offset(1).execute::<MyObject>().await.unwrap();
231+
/// # index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
150232
/// # });
151233
/// ```
152234
pub async fn execute<T: DeserializeOwned + 'static>(

src/indexes.rs

Lines changed: 62 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -285,29 +285,21 @@ impl Index {
285285
/// # let MEILISEARCH_HOST = option_env!("MEILISEARCH_HOST").unwrap_or("http://localhost:7700");
286286
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
287287
/// #
288-
/// #[derive(Serialize, Debug)]
288+
/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
289289
/// struct Movie {
290290
/// name: String,
291-
/// description: String,
292-
/// age: Option<usize>
293-
/// }
294-
///
295-
/// #[derive(Deserialize, Debug, PartialEq)]
296-
/// struct ReturnedMovie {
297-
/// name: String,
298291
/// description: String
299292
/// }
300293
///
301-
///
302294
/// # futures::executor::block_on(async move {
303295
/// let client = Client::new(MEILISEARCH_HOST, MEILISEARCH_API_KEY);
304296
/// let movies = client.index("get_document");
305-
/// # movies.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage."), age: Some(1)}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
297+
/// # movies.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
306298
///
307299
/// // retrieve a document (you have to put the document in the index before)
308-
/// let interstellar = movies.get_document::<ReturnedMovie>("Interstellar", Some(["name", "description"].to_vec())).await.unwrap();
300+
/// let interstellar = movies.get_document::<Movie>("Interstellar").await.unwrap();
309301
///
310-
/// assert_eq!(interstellar, ReturnedMovie {
302+
/// assert_eq!(interstellar, Movie {
311303
/// name: String::from("Interstellar"),
312304
/// description: String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage."),
313305
/// });
@@ -317,16 +309,65 @@ impl Index {
317309
pub async fn get_document<T: 'static + DeserializeOwned>(
318310
&self,
319311
document_id: &str,
320-
fields: Option<Vec<&str>>,
321312
) -> Result<T, Error> {
322313
let url = format!(
323314
"{}/indexes/{}/documents/{}",
324315
self.client.host, self.uid, document_id
325316
);
326317

327-
let query = DocumentQuery { fields };
318+
request::<(), T>(&url, &self.client.api_key, Method::Get(()), 200).await
319+
}
320+
321+
/// Get one document with parameters.
322+
///
323+
/// # Example
324+
///
325+
/// ```
326+
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
327+
/// # use serde::{Deserialize, Serialize};
328+
/// #
329+
/// # let MEILISEARCH_HOST = option_env!("MEILISEARCH_HOST").unwrap_or("http://localhost:7700");
330+
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
331+
/// #
332+
/// # let client = Client::new(MEILISEARCH_HOST, MEILISEARCH_API_KEY);
333+
///
334+
/// # futures::executor::block_on(async move {
335+
/// #[derive(Debug, Serialize, Deserialize, PartialEq)]
336+
/// struct MyObject {
337+
/// id: String,
338+
/// kind: String,
339+
/// }
340+
/// #[derive(Debug, Serialize, Deserialize, PartialEq)]
341+
/// struct MyObjectReduced {
342+
/// id: String,
343+
/// }
344+
///
345+
/// # let index = client.index("document_query_execute");
346+
/// # index.add_or_replace(&[MyObject{id:"1".to_string(), kind:String::from("a kind")},MyObject{id:"2".to_string(), kind:String::from("some kind")}], None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
347+
///
348+
/// let mut document_query = DocumentQuery::new(&index);
349+
/// document_query.with_fields(["id"]);
350+
///
351+
/// let document = index.get_document_with::<MyObjectReduced>("1", &document_query).await.unwrap();
352+
///
353+
/// assert_eq!(
354+
/// document,
355+
/// MyObjectReduced { id: "1".to_string() }
356+
/// );
357+
/// # index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
358+
/// # });
359+
pub async fn get_document_with<T: 'static + DeserializeOwned>(
360+
&self,
361+
document_id: &str,
362+
document_query: &DocumentQuery<'_>,
363+
) -> Result<T, Error> {
364+
let url = format!(
365+
"{}/indexes/{}/documents/{}",
366+
self.client.host, self.uid, document_id
367+
);
328368

329-
request::<&DocumentQuery, T>(&url, &self.client.api_key, Method::Get(&query), 200).await
369+
request::<&DocumentQuery, T>(&url, &self.client.api_key, Method::Get(document_query), 200)
370+
.await
330371
}
331372

332373
/// Get [Document]s by batch.
@@ -388,6 +429,10 @@ impl Index {
388429
/// description: String,
389430
/// }
390431
///
432+
/// #[derive(Deserialize, Debug, PartialEq)]
433+
/// struct ReturnedMovie {
434+
/// name: String,
435+
/// }
391436
///
392437
/// # futures::executor::block_on(async move {
393438
/// let client = Client::new(MEILISEARCH_HOST, MEILISEARCH_API_KEY);
@@ -397,8 +442,9 @@ impl Index {
397442
///
398443
/// let mut query = DocumentsQuery::new(&movie_index);
399444
/// query.with_limit(1);
445+
/// query.with_fields(["name"]);
400446
/// // retrieve movies (you have to put some movies in the index before)
401-
/// let movies = movie_index.get_documents_with::<Movie>(&query).await.unwrap();
447+
/// let movies = movie_index.get_documents_with::<ReturnedMovie>(&query).await.unwrap();
402448
///
403449
/// assert!(movies.results.len() == 1);
404450
/// # movie_index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();

0 commit comments

Comments
 (0)