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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
/// Derive the [`IndexConfig`](crate::documents::IndexConfig) trait.
///
/// ## Field attribute
/// Use the `#[index_config(..)]` field attribute to generate the correct settings
/// for each field. The available parameters are:
/// - `primary_key` (can only be used once)
/// - `distinct` (can only be used once)
/// - `searchable`
/// - `displayed`
/// - `filterable`
/// - `sortable`
///
/// ## Index name
/// The name of the index will be the name of the struct converted to snake case.
///
/// ## Sample usage:
/// ```
/// use serde::{Serialize, Deserialize};
/// use meilisearch_sdk::documents::IndexConfig;
/// use meilisearch_sdk::settings::Settings;
/// use meilisearch_sdk::indexes::Index;
/// use meilisearch_sdk::client::Client;
///
/// #[derive(Serialize, Deserialize, IndexConfig)]
/// struct Movie {
/// #[index_config(primary_key)]
/// movie_id: u64,
/// #[index_config(displayed, searchable)]
/// title: String,
/// #[index_config(displayed)]
/// description: String,
/// #[index_config(filterable, sortable, displayed)]
/// release_date: String,
/// #[index_config(filterable, displayed)]
/// genres: Vec<String>,
/// }
///
/// async fn usage(client: Client) {
/// // Default settings with the distinct, searchable, displayed, filterable, and sortable fields set correctly.
/// let settings: Settings = Movie::generate_settings();
/// // Index created with the name `movie` and the primary key set to `movie_id`
/// let index: Index = Movie::generate_index(&client).await.unwrap();
/// }
/// ```
pub use meilisearch_index_setting_macro::IndexConfig;
use crate::client::Client;
use crate::request::HttpClient;
use crate::settings::Settings;
use crate::task_info::TaskInfo;
use crate::tasks::Task;
use crate::{errors::Error, indexes::Index};
#[async_trait(?Send)]
pub trait IndexConfig {
const INDEX_STR: &'static str;
#[must_use]
fn index<Http: HttpClient>(client: &Client<Http>) -> Index<Http> {
client.index(Self::INDEX_STR)
}
fn generate_settings() -> Settings;
async fn generate_index<Http: HttpClient>(client: &Client<Http>) -> Result<Index<Http>, Task>;
}
#[derive(Debug, Clone, Deserialize)]
pub struct DocumentsResults<T> {
pub results: Vec<T>,
pub limit: u32,
pub offset: u32,
pub total: u32,
}
#[derive(Debug, Clone, Serialize)]
pub struct DocumentQuery<'a, Http: HttpClient> {
#[serde(skip_serializing)]
pub index: &'a Index<Http>,
/// The fields that should appear in the documents. By default, all of the fields are present.
#[serde(skip_serializing_if = "Option::is_none")]
pub fields: Option<Vec<&'a str>>,
}
impl<'a, Http: HttpClient> DocumentQuery<'a, Http> {
#[must_use]
pub fn new(index: &Index<Http>) -> DocumentQuery<Http> {
DocumentQuery {
index,
fields: None,
}
}
/// Specify the fields to return in the document.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// let index = client.index("document_query_with_fields");
/// let mut document_query = DocumentQuery::new(&index);
///
/// document_query.with_fields(["title"]);
/// ```
pub fn with_fields(
&mut self,
fields: impl IntoIterator<Item = &'a str>,
) -> &mut DocumentQuery<'a, Http> {
self.fields = Some(fields.into_iter().collect());
self
}
/// Execute the get document query.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
/// # use serde::{Deserialize, Serialize};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
/// #[derive(Debug, Serialize, Deserialize, PartialEq)]
/// struct MyObject {
/// id: String,
/// kind: String,
/// }
///
/// #[derive(Debug, Serialize, Deserialize, PartialEq)]
/// struct MyObjectReduced {
/// id: String,
/// }
/// # let index = client.index("document_query_execute");
/// # 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();
///
/// let document = DocumentQuery::new(&index).with_fields(["id"])
/// .execute::<MyObjectReduced>("1")
/// .await
/// .unwrap();
///
/// assert_eq!(
/// document,
/// MyObjectReduced { id: "1".to_string() }
/// );
/// # index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
pub async fn execute<T: DeserializeOwned + 'static + Send + Sync>(
&self,
document_id: &str,
) -> Result<T, Error> {
self.index.get_document_with::<T>(document_id, self).await
}
}
#[derive(Debug, Clone, Serialize)]
pub struct DocumentsQuery<'a, Http: HttpClient> {
#[serde(skip_serializing)]
pub index: &'a Index<Http>,
/// The number of documents to skip.
///
/// If the value of the parameter `offset` is `n`, the `n` first documents will not be returned.
/// This is helpful for pagination.
///
/// Example: If you want to skip the first document, set offset to `1`.
#[serde(skip_serializing_if = "Option::is_none")]
pub offset: Option<usize>,
/// The maximum number of documents returned.
/// If the value of the parameter `limit` is `n`, there will never be more than `n` documents in the response.
/// This is helpful for pagination.
///
/// Example: If you don't want to get more than two documents, set limit to `2`.
///
/// **Default: `20`**
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
/// The fields that should appear in the documents. By default, all of the fields are present.
#[serde(skip_serializing_if = "Option::is_none")]
pub fields: Option<Vec<&'a str>>,
/// Filters to apply.
///
/// Available since v1.2 of Meilisearch
/// Read the [dedicated guide](https://www.meilisearch.com/docs/learn/fine_tuning_results/filtering#filter-basics) to learn the syntax.
#[serde(skip_serializing_if = "Option::is_none")]
pub filter: Option<&'a str>,
}
impl<'a, Http: HttpClient> DocumentsQuery<'a, Http> {
#[must_use]
pub fn new(index: &Index<Http>) -> DocumentsQuery<Http> {
DocumentsQuery {
index,
offset: None,
limit: None,
fields: None,
filter: None,
}
}
/// Specify the offset.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// let index = client.index("my_index");
///
/// let mut documents_query = DocumentsQuery::new(&index).with_offset(1);
/// ```
pub fn with_offset(&mut self, offset: usize) -> &mut DocumentsQuery<'a, Http> {
self.offset = Some(offset);
self
}
/// Specify the limit.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// let index = client.index("my_index");
///
/// let mut documents_query = DocumentsQuery::new(&index);
///
/// documents_query.with_limit(1);
/// ```
pub fn with_limit(&mut self, limit: usize) -> &mut DocumentsQuery<'a, Http> {
self.limit = Some(limit);
self
}
/// Specify the fields to return in the documents.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// let index = client.index("my_index");
///
/// let mut documents_query = DocumentsQuery::new(&index);
///
/// documents_query.with_fields(["title"]);
/// ```
pub fn with_fields(
&mut self,
fields: impl IntoIterator<Item = &'a str>,
) -> &mut DocumentsQuery<'a, Http> {
self.fields = Some(fields.into_iter().collect());
self
}
pub fn with_filter<'b>(&'b mut self, filter: &'a str) -> &'b mut DocumentsQuery<'a, Http> {
self.filter = Some(filter);
self
}
/// Execute the get documents query.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, documents::*};
/// # use serde::{Deserialize, Serialize};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
/// # let index = client.create_index("documents_query_execute", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap();
/// #[derive(Debug, Serialize, Deserialize, PartialEq)]
/// struct MyObject {
/// id: Option<usize>,
/// kind: String,
/// }
/// let index = client.index("documents_query_execute");
///
/// let document = DocumentsQuery::new(&index)
/// .with_offset(1)
/// .execute::<MyObject>()
/// .await
/// .unwrap();
///
/// # index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
/// ```
pub async fn execute<T: DeserializeOwned + 'static + Send + Sync>(
&self,
) -> Result<DocumentsResults<T>, Error> {
self.index.get_documents_with::<T>(self).await
}
}
#[derive(Debug, Clone, Serialize)]
pub struct DocumentDeletionQuery<'a, Http: HttpClient> {
#[serde(skip_serializing)]
pub index: &'a Index<Http>,
/// Filters to apply.
///
/// Read the [dedicated guide](https://www.meilisearch.com/docs/learn/fine_tuning_results/filtering#filter-basics) to learn the syntax.
pub filter: Option<&'a str>,
}
impl<'a, Http: HttpClient> DocumentDeletionQuery<'a, Http> {
#[must_use]
pub fn new(index: &Index<Http>) -> DocumentDeletionQuery<Http> {
DocumentDeletionQuery {
index,
filter: None,
}
}
pub fn with_filter<'b>(
&'b mut self,
filter: &'a str,
) -> &'b mut DocumentDeletionQuery<'a, Http> {
self.filter = Some(filter);
self
}
pub async fn execute<T: DeserializeOwned + 'static>(&self) -> Result<TaskInfo, Error> {
self.index.delete_documents_with(self).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{client::Client, errors::*, indexes::*};
use meilisearch_test_macro::meilisearch_test;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct MyObject {
id: Option<usize>,
kind: String,
}
#[allow(unused)]
#[derive(IndexConfig)]
struct MovieClips {
#[index_config(primary_key)]
movie_id: u64,
#[index_config(distinct)]
owner: String,
#[index_config(displayed, searchable)]
title: String,
#[index_config(displayed)]
description: String,
#[index_config(filterable, sortable, displayed)]
release_date: String,
#[index_config(filterable, displayed)]
genres: Vec<String>,
}
#[allow(unused)]
#[derive(IndexConfig)]
struct VideoClips {
video_id: u64,
}
async fn setup_test_index(client: &Client, index: &Index) -> Result<(), Error> {
let t0 = index
.add_documents(
&[
MyObject {
id: Some(0),
kind: "text".into(),
},
MyObject {
id: Some(1),
kind: "text".into(),
},
MyObject {
id: Some(2),
kind: "title".into(),
},
MyObject {
id: Some(3),
kind: "title".into(),
},
],
None,
)
.await?;
t0.wait_for_completion(client, None, None).await?;
Ok(())
}
#[meilisearch_test]
async fn test_get_documents_with_execute(client: Client, index: Index) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
let documents = DocumentsQuery::new(&index)
.with_limit(1)
.with_offset(1)
.with_fields(["kind"])
.execute::<MyObject>()
.await
.unwrap();
assert_eq!(documents.limit, 1);
assert_eq!(documents.offset, 1);
assert_eq!(documents.results.len(), 1);
Ok(())
}
#[meilisearch_test]
async fn test_delete_documents_with(client: Client, index: Index) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
index
.set_filterable_attributes(["id"])
.await?
.wait_for_completion(&client, None, None)
.await?;
let mut query = DocumentDeletionQuery::new(&index);
query.with_filter("id = 1");
index
.delete_documents_with(&query)
.await?
.wait_for_completion(&client, None, None)
.await?;
let document_result = index.get_document::<MyObject>("1").await;
match document_result {
Ok(_) => panic!("The test was expecting no documents to be returned but got one."),
Err(e) => match e {
Error::Meilisearch(err) => {
assert_eq!(err.error_code, ErrorCode::DocumentNotFound);
}
_ => panic!("The error was expected to be a Meilisearch error, but it was not."),
},
}
Ok(())
}
#[meilisearch_test]
async fn test_delete_documents_with_filter_not_filterable(
client: Client,
index: Index,
) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
let mut query = DocumentDeletionQuery::new(&index);
query.with_filter("id = 1");
let error = index
.delete_documents_with(&query)
.await?
.wait_for_completion(&client, None, None)
.await?;
let error = error.unwrap_failure();
assert!(matches!(
error,
MeilisearchError {
error_code: ErrorCode::InvalidDocumentFilter,
error_type: ErrorType::InvalidRequest,
..
}
));
Ok(())
}
#[meilisearch_test]
async fn test_get_documents_with_only_one_param(
client: Client,
index: Index,
) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
// let documents = index.get_documents(None, None, None).await.unwrap();
let documents = DocumentsQuery::new(&index)
.with_limit(1)
.execute::<MyObject>()
.await
.unwrap();
assert_eq!(documents.limit, 1);
assert_eq!(documents.offset, 0);
assert_eq!(documents.results.len(), 1);
Ok(())
}
#[meilisearch_test]
async fn test_get_documents_with_filter(client: Client, index: Index) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
index
.set_filterable_attributes(["id"])
.await
.unwrap()
.wait_for_completion(&client, None, None)
.await
.unwrap();
let documents = DocumentsQuery::new(&index)
.with_filter("id = 1")
.execute::<MyObject>()
.await?;
assert_eq!(documents.results.len(), 1);
Ok(())
}
#[meilisearch_test]
async fn test_get_documents_with_error_hint() -> Result<(), Error> {
let meilisearch_url = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
let client = Client::new(format!("{meilisearch_url}/hello"), Some("masterKey")).unwrap();
let index = client.index("test_get_documents_with_filter_wrong_ms_version");
let documents = DocumentsQuery::new(&index)
.with_filter("id = 1")
.execute::<MyObject>()
.await;
let error = documents.unwrap_err();
let message = Some("Hint: It might not be working because you're not up to date with the Meilisearch version that updated the get_documents_with method.".to_string());
let url = format!(
"{meilisearch_url}/hello/indexes/test_get_documents_with_filter_wrong_ms_version/documents/fetch"
);
let status_code = 404;
let displayed_error = format!("MeilisearchCommunicationError: The server responded with a 404. Hint: It might not be working because you're not up to date with the Meilisearch version that updated the get_documents_with method.\nurl: {meilisearch_url}/hello/indexes/test_get_documents_with_filter_wrong_ms_version/documents/fetch");
match &error {
Error::MeilisearchCommunication(error) => {
assert_eq!(error.status_code, status_code);
assert_eq!(error.message, message);
assert_eq!(error.url, url);
}
_ => panic!("The error was expected to be a MeilisearchCommunicationError error, but it was not."),
};
assert_eq!(format!("{error}"), displayed_error);
Ok(())
}
#[meilisearch_test]
async fn test_get_documents_with_error_hint_meilisearch_api_error(
index: Index,
client: Client,
) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
let error = DocumentsQuery::new(&index)
.with_filter("id = 1")
.execute::<MyObject>()
.await
.unwrap_err();
let message = "Attribute `id` is not filterable. This index does not have configured filterable attributes.
1:3 id = 1
Hint: It might not be working because you're not up to date with the Meilisearch version that updated the get_documents_with method.".to_string();
let displayed_error = "Meilisearch invalid_request: invalid_document_filter: Attribute `id` is not filterable. This index does not have configured filterable attributes.
1:3 id = 1
Hint: It might not be working because you're not up to date with the Meilisearch version that updated the get_documents_with method.. https://docs.meilisearch.com/errors#invalid_document_filter";
match &error {
Error::Meilisearch(error) => {
assert_eq!(error.error_message, message);
}
_ => panic!("The error was expected to be a MeilisearchCommunicationError error, but it was not."),
};
assert_eq!(format!("{error}"), displayed_error);
Ok(())
}
#[meilisearch_test]
async fn test_get_documents_with_invalid_filter(
client: Client,
index: Index,
) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
// Does not work because `id` is not filterable
let error = DocumentsQuery::new(&index)
.with_filter("id = 1")
.execute::<MyObject>()
.await
.unwrap_err();
assert!(matches!(
error,
Error::Meilisearch(MeilisearchError {
error_code: ErrorCode::InvalidDocumentFilter,
error_type: ErrorType::InvalidRequest,
..
})
));
Ok(())
}
#[meilisearch_test]
async fn test_settings_generated_by_macro(client: Client, index: Index) -> Result<(), Error> {
setup_test_index(&client, &index).await?;
let movie_settings: Settings = MovieClips::generate_settings();
let video_settings: Settings = VideoClips::generate_settings();
assert_eq!(movie_settings.searchable_attributes.unwrap(), ["title"]);
assert!(video_settings.searchable_attributes.unwrap().is_empty());
assert_eq!(
movie_settings.displayed_attributes.unwrap(),
["title", "description", "release_date", "genres"]
);
assert!(video_settings.displayed_attributes.unwrap().is_empty());
assert_eq!(
movie_settings.filterable_attributes.unwrap(),
["release_date", "genres"]
);
assert!(video_settings.filterable_attributes.unwrap().is_empty());
assert_eq!(
movie_settings.sortable_attributes.unwrap(),
["release_date"]
);
assert!(video_settings.sortable_attributes.unwrap().is_empty());
Ok(())
}
#[meilisearch_test]
async fn test_generate_index(client: Client) -> Result<(), Error> {
let index: Index = MovieClips::generate_index(&client).await.unwrap();
assert_eq!(index.uid, "movie_clips");
index
.delete()
.await?
.wait_for_completion(&client, None, None)
.await?;
Ok(())
}
#[derive(Serialize, Deserialize, IndexConfig)]
struct Movie {
#[index_config(primary_key)]
movie_id: u64,
#[index_config(displayed, searchable)]
title: String,
#[index_config(displayed)]
description: String,
#[index_config(filterable, sortable, displayed)]
release_date: String,
#[index_config(filterable, displayed)]
genres: Vec<String>,
}
}