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 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
use crate::{ client::Client, document::*, errors::Error, progress::*, request::*, search::*, settings::*, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::json; use std::fmt::Display; #[derive(Deserialize, Debug)] #[allow(non_snake_case)] pub(crate) struct JsonIndex { uid: String, primaryKey: Option<String>, createdAt: String, updatedAt: String, } impl JsonIndex { pub(crate) fn into_index<'a>(self, client: &'a Client) -> Index<'a> { Index { uid: self.uid, client, } } } /// An index containing [Documents](../document/trait.Document.html). /// /// # Example /// /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// let client = Client::new("http://localhost:7700", ""); /// /// // get the index called movies or create it if it does not exist /// let movies = client.get_or_create("movies").unwrap(); /// /// // do something with the index /// ``` #[derive(Debug)] pub struct Index<'a> { pub(crate) uid: String, pub(crate) client: &'a Client<'a>, } impl<'a> Index<'a> { /// Set the primary key of the index. /// /// If you prefer, you can use the method [set_primary_key](#method.set_primary_key), which is an alias. #[cfg(not(target_arch = "wasm32"))] pub fn update(&mut self, primary_key: &str) -> Result<(), Error> { request::<serde_json::Value, JsonIndex>( &format!("{}/indexes/{}", self.client.host, self.uid), self.client.apikey, Method::Put(json!({ "primaryKey": primary_key })), 200, )?; Ok(()) } #[cfg(target_arch = "wasm32")] pub async fn update(&mut self, primary_key: &str) -> Result<(), Error> { request::<serde_json::Value, JsonIndex>( &format!("{}/indexes/{}", self.client.host, self.uid), self.client.apikey, Method::Put(json!({ "primaryKey": primary_key })), 200, ).await?; Ok(()) } /// Delete the index. /// /// # Example /// /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// let client = Client::new("http://localhost:7700", ""); /// # client.create_index("movies", None); /// /// // get the index named "movies" and delete it /// let movies = client.get_index("movies").unwrap(); /// movies.delete().unwrap(); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn delete(self) -> Result<(), Error> { Ok(request::<(), ()>( &format!("{}/indexes/{}", self.client.host, self.uid), self.client.apikey, Method::Delete, 204, )?) } #[cfg(target_arch = "wasm32")] pub async fn delete(self) -> Result<(), Error> { Ok(request::<(), ()>( &format!("{}/indexes/{}", self.client.host, self.uid), self.client.apikey, Method::Delete, 204, ).await?) } /// Search for documents matching a specific query in the index. /// /// # Example /// /// ``` /// use serde::{Serialize, Deserialize}; /// # use meilisearch_sdk::{client::*, indexes::*, document::*, search::*}; /// /// #[derive(Serialize, Deserialize, Debug)] /// struct Movie { /// name: String, /// description: String, /// } /// // that trait is used by the sdk when the primary key is needed /// impl Document for Movie { /// type UIDType = String; /// fn get_uid(&self) -> &Self::UIDType { /// &self.name /// } /// } /// /// let client = Client::new("http://localhost:7700", ""); /// let mut movies = client.get_or_create("movies").unwrap(); /// /// // add some documents /// # movies.add_or_replace(vec![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.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).unwrap(); /// # std::thread::sleep(std::time::Duration::from_secs(1)); /// /// let query = Query::new("Interstellar").with_limit(5); /// let results = movies.search::<Movie>(&query).unwrap(); /// # assert!(results.hits.len()>0); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn search<T: 'static + DeserializeOwned>( &self, query: &Query, ) -> Result<SearchResults<T>, Error> { Ok(request::<(), SearchResults<T>>( &format!( "{}/indexes/{}/search{}", self.client.host, self.uid, query.to_url() ), self.client.apikey, Method::Get, 200, )?) } #[cfg(target_arch = "wasm32")] pub async fn search<T: 'static + DeserializeOwned>( &self, query: &Query<'_>, ) -> Result<SearchResults<T>, Error> { Ok(request::<(), SearchResults<T>>( &format!( "{}/indexes/{}/search{}", self.client.host, self.uid, query.to_url() ), self.client.apikey, Method::Get, 200, ).await?) } /// Get one [document](../document/trait.Document.html) using its unique id. /// Serde is needed. Add `serde = {version="1.0", features=["derive"]}` in the dependencies section of your Cargo.toml. /// /// # Example /// /// ``` /// use serde::{Serialize, Deserialize}; /// /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// let client = Client::new("http://localhost:7700", ""); /// # client.create_index("movies", None); /// let movies = client.get_index("movies").unwrap(); /// # let mut movies = client.get_index("movies").unwrap(); /// /// #[derive(Serialize, Deserialize, Debug)] /// # #[derive(PartialEq)] /// struct Movie { /// name: String, /// description: String, /// } /// /// // that trait is used by the sdk when the primary key is needed /// impl Document for Movie { /// type UIDType = String; /// fn get_uid(&self) -> &Self::UIDType { /// &self.name /// } /// } /// /// # movies.add_or_replace(vec![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")).unwrap(); /// # std::thread::sleep(std::time::Duration::from_secs(1)); /// # /// // retrieve a document (you have to put the document in the index before) /// let interstellar = movies.get_document::<Movie>(String::from("Interstellar")).unwrap(); /// /// assert_eq!(interstellar, 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.") /// }); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn get_document<T: 'static + Document>(&self, uid: T::UIDType) -> Result<T, Error> { Ok(request::<(), T>( &format!( "{}/indexes/{}/documents/{}", self.client.host, self.uid, uid ), self.client.apikey, Method::Get, 200, )?) } #[cfg(target_arch = "wasm32")] pub async fn get_document<T: 'static + Document>(&self, uid: T::UIDType) -> Result<T, Error> { Ok(request::<(), T>( &format!( "{}/indexes/{}/documents/{}", self.client.host, self.uid, uid ), self.client.apikey, Method::Get, 200, ).await?) } /// Get [documents](../document/trait.Document.html) by batch. /// /// Using the optional parameters offset and limit, you can browse through all your documents. /// If None, offset will be set to 0, limit to 20, and all attributes will be retrieved. /// /// *Note: Documents are ordered by MeiliSearch depending on the hash of their id.* /// /// # Example /// /// ``` /// use serde::{Serialize, Deserialize}; /// /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// let client = Client::new("http://localhost:7700", ""); /// # client.create_index("movies", None); /// let movie_index = client.get_index("movies").unwrap(); /// # let mut movie_index = client.get_index("movies").unwrap(); /// /// #[derive(Serialize, Deserialize, Debug)] /// # #[derive(PartialEq)] /// struct Movie { /// name: String, /// description: String, /// } /// /// // that trait is used by the sdk when the primary key is needed /// impl Document for Movie { /// type UIDType = String; /// fn get_uid(&self) -> &Self::UIDType { /// &self.name /// } /// } /// /// # movie_index.add_or_replace(vec![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")).unwrap(); /// # std::thread::sleep(std::time::Duration::from_secs(1)); /// # /// // retrieve movies (you have to put some movies in the index before) /// let movies = movie_index.get_documents::<Movie>(None, None, None).unwrap(); /// /// assert!(movies.len() > 0); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn get_documents<T: 'static + Document>( &self, offset: Option<usize>, limit: Option<usize>, attributes_to_retrieve: Option<&str>, ) -> Result<Vec<T>, Error> { let mut url = format!("{}/indexes/{}/documents?", self.client.host, self.uid); if let Some(offset) = offset { url.push_str("offset="); url.push_str(offset.to_string().as_str()); url.push_str("&"); } if let Some(limit) = limit { url.push_str("limit="); url.push_str(limit.to_string().as_str()); url.push_str("&"); } if let Some(attributes_to_retrieve) = attributes_to_retrieve { url.push_str("attributesToRetrieve="); url.push_str(attributes_to_retrieve.to_string().as_str()); } Ok(request::<(), Vec<T>>( &url, self.client.apikey, Method::Get, 200, )?) } #[cfg(target_arch = "wasm32")] pub async fn get_documents<T: 'static + Document>( &self, offset: Option<usize>, limit: Option<usize>, attributes_to_retrieve: Option<&str>, ) -> Result<Vec<T>, Error> { let mut url = format!("{}/indexes/{}/documents?", self.client.host, self.uid); if let Some(offset) = offset { url.push_str("offset="); url.push_str(offset.to_string().as_str()); url.push_str("&"); } if let Some(limit) = limit { url.push_str("limit="); url.push_str(limit.to_string().as_str()); url.push_str("&"); } if let Some(attributes_to_retrieve) = attributes_to_retrieve { url.push_str("attributesToRetrieve="); url.push_str(attributes_to_retrieve.to_string().as_str()); } Ok(request::<(), Vec<T>>( &url, self.client.apikey, Method::Get, 200, ).await?) } /// Add a list of [documents](../document/trait.Document.html) or replace them if they already exist. /// /// If you send an already existing document (same id) the **whole existing document** will be overwritten by the new document. /// Fields previously in the document not present in the new document are removed. /// /// For a partial update of the document see [add_or_update](#method.add_or_update). /// /// You can use the alias [add_documents](#method.add_documents) if you prefer. /// /// # Example /// /// ``` /// use serde::{Serialize, Deserialize}; /// /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// # use std::thread::sleep; /// # use std::time::Duration; /// let client = Client::new("http://localhost:7700", ""); /// let mut movie_index = client.get_or_create("movies").unwrap(); /// /// #[derive(Serialize, Deserialize, Debug)] /// struct Movie { /// name: String, /// description: String, /// } /// // that trait is used by the sdk when the primary key is needed /// impl Document for Movie { /// type UIDType = String; /// fn get_uid(&self) -> &Self::UIDType { /// &self.name /// } /// } /// /// movie_index.add_or_replace(vec![ /// 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.") /// }, /// Movie{ /// // note that the id field can only take alphanumerics characters (and '-' and '/') /// name: String::from("MrsDoubtfire"), /// description: String::from("Loving but irresponsible dad Daniel Hillard, estranged from his exasperated spouse, is crushed by a court order allowing only weekly visits with his kids. When Daniel learns his ex needs a housekeeper, he gets the job -- disguised as an English nanny. Soon he becomes not only his children's best pal but the kind of parent he should have been from the start.") /// }, /// Movie{ /// name: String::from("Apollo13"), /// description: String::from("The true story of technical troubles that scuttle the Apollo 13 lunar mission in 1971, risking the lives of astronaut Jim Lovell and his crew, with the failed journey turning into a thrilling saga of heroism. Drifting more than 200,000 miles from Earth, the astronauts work furiously with the ground crew to avert tragedy.") /// }, /// ], Some("name")).unwrap(); /// sleep(Duration::from_secs(1)); // MeiliSearch may take some time to execute the request /// /// // retrieve movies (you have to put some movies in the index before) /// let movies = movie_index.get_documents::<Movie>(None, None, None).unwrap(); /// assert!(movies.len() >= 3); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn add_or_replace<T: Document>( &mut self, documents: Vec<T>, primary_key: Option<&str>, ) -> Result<Progress, Error> { let url = if let Some(primary_key) = primary_key { format!( "{}/indexes/{}/documents?primaryKey={}", self.client.host, self.uid, primary_key ) } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; Ok( request::<Vec<T>, ProgressJson>( &url, self.client.apikey, Method::Post(documents), 202, )? .into_progress(self), ) } #[cfg(target_arch = "wasm32")] pub async fn add_or_replace<T: Document>( &'a self, documents: Vec<T>, primary_key: Option<&str>, ) -> Result<Progress<'a>, Error> { let url = if let Some(primary_key) = primary_key { format!( "{}/indexes/{}/documents?primaryKey={}", self.client.host, self.uid, primary_key ) } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; Ok( request::<Vec<T>, ProgressJson>( &url, self.client.apikey, Method::Post(documents), 202, ).await? .into_progress(self), ) } /// Alias for [add_or_replace](#method.add_or_replace). #[cfg(not(target_arch = "wasm32"))] pub fn add_documents<T: Document>( &mut self, documents: Vec<T>, primary_key: Option<&str>, ) -> Result<Progress, Error> { self.add_or_replace(documents, primary_key) } #[cfg(target_arch = "wasm32")] pub async fn add_documents<T: Document>( &'a self, documents: Vec<T>, primary_key: Option<&str>, ) -> Result<Progress<'a>, Error> { self.add_or_replace(documents, primary_key).await } /// Add a list of documents and update them if they already. /// /// If you send an already existing document (same id) the old document will be only partially updated according to the fields of the new document. /// Thus, any fields not present in the new document are kept and remained unchanged. /// /// To completely overwrite a document, check out the [add_and_replace documents](#method.add_or_replace) method. /// /// # Example /// /// ``` /// use serde::{Serialize, Deserialize}; /// /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// # use std::thread::sleep; /// # use std::time::Duration; /// let client = Client::new("http://localhost:7700", ""); /// let mut movie_index = client.get_or_create("movies").unwrap(); /// /// #[derive(Serialize, Deserialize, Debug)] /// struct Movie { /// name: String, /// description: String, /// } /// // that trait is used by the sdk when the primary key is needed /// impl Document for Movie { /// type UIDType = String; /// fn get_uid(&self) -> &Self::UIDType { /// &self.name /// } /// } /// /// movie_index.add_or_update(vec![ /// 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.") /// }, /// Movie{ /// // note that the id field can only take alphanumerics characters (and '-' and '/') /// name: String::from("MrsDoubtfire"), /// description: String::from("Loving but irresponsible dad Daniel Hillard, estranged from his exasperated spouse, is crushed by a court order allowing only weekly visits with his kids. When Daniel learns his ex needs a housekeeper, he gets the job -- disguised as an English nanny. Soon he becomes not only his children's best pal but the kind of parent he should have been from the start.") /// }, /// Movie{ /// name: String::from("Apollo13"), /// description: String::from("The true story of technical troubles that scuttle the Apollo 13 lunar mission in 1971, risking the lives of astronaut Jim Lovell and his crew, with the failed journey turning into a thrilling saga of heroism. Drifting more than 200,000 miles from Earth, the astronauts work furiously with the ground crew to avert tragedy.") /// }, /// ], Some("name")).unwrap(); /// sleep(Duration::from_secs(1)); // MeiliSearch may take some time to execute the request /// /// // retrieve movies (you have to put some movies in the index before) /// let movies = movie_index.get_documents::<Movie>(None, None, None).unwrap(); /// assert!(movies.len() >= 3); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn add_or_update<T: Document>( &mut self, documents: Vec<T>, primary_key: Option<&str>, ) -> Result<Progress, Error> { let url = if let Some(primary_key) = primary_key { format!( "{}/indexes/{}/documents?primaryKey={}", self.client.host, self.uid, primary_key ) } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; Ok( request::<Vec<T>, ProgressJson>(&url, self.client.apikey, Method::Put(documents), 202)? .into_progress(self), ) } #[cfg(target_arch = "wasm32")] pub async fn add_or_update<T: Document>( &'a self, documents: Vec<T>, primary_key: Option<&str>, ) -> Result<Progress<'a>, Error> { let url = if let Some(primary_key) = primary_key { format!( "{}/indexes/{}/documents?primaryKey={}", self.client.host, self.uid, primary_key ) } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; Ok( request::<Vec<T>, ProgressJson>(&url, self.client.apikey, Method::Put(documents), 202).await? .into_progress(self), ) } /// Delete all documents in the index. /// /// # Example /// /// ``` /// # use serde::{Serialize, Deserialize}; /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// # /// # #[derive(Serialize, Deserialize, Debug)] /// # struct Movie { /// # name: String, /// # description: String, /// # } /// # /// # // that trait is used by the sdk when the primary key is needed /// # impl Document for Movie { /// # type UIDType = String; /// # fn get_uid(&self) -> &Self::UIDType { /// # &self.name /// # } /// # } /// # /// let client = Client::new("http://localhost:7700", ""); /// let mut movie_index = client.get_or_create("movies").unwrap(); /// /// // add some documents /// /// movie_index.delete_all_documents().unwrap(); /// # let movies = movie_index.get_documents::<Movie>(None, None, None).unwrap(); /// # assert_eq!(movies.len(), 0); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn delete_all_documents(&mut self) -> Result<Progress, Error> { Ok(request::<(), ProgressJson>( &format!("{}/indexes/{}/documents", self.client.host, self.uid), self.client.apikey, Method::Delete, 202, )? .into_progress(self)) } #[cfg(target_arch = "wasm32")] pub async fn delete_all_documents(&'a self) -> Result<Progress<'a>, Error> { Ok(request::<(), ProgressJson>( &format!("{}/indexes/{}/documents", self.client.host, self.uid), self.client.apikey, Method::Delete, 202, ).await? .into_progress(self)) } /// Delete one document based on its unique id. /// /// # Example /// /// ``` /// # use serde::{Serialize, Deserialize}; /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// # /// # #[derive(Serialize, Deserialize, Debug)] /// # struct Movie { /// # name: String, /// # description: String, /// # } /// # /// # // that trait is used by the sdk when the primary key is needed /// # impl Document for Movie { /// # type UIDType = String; /// # fn get_uid(&self) -> &Self::UIDType { /// # &self.name /// # } /// # } /// # /// # /// let client = Client::new("http://localhost:7700", ""); /// let mut movies = client.get_or_create("movies").unwrap(); /// /// # movies.add_or_replace(vec![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")).unwrap(); /// # std::thread::sleep(std::time::Duration::from_secs(1)); /// // add a document with id = Interstellar /// /// movies.delete_document("Interstellar").unwrap(); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn delete_document<T: Display>(&mut self, uid: T) -> Result<Progress, Error> { Ok(request::<(), ProgressJson>( &format!( "{}/indexes/{}/documents/{}", self.client.host, self.uid, uid ), self.client.apikey, Method::Delete, 202, )? .into_progress(self)) } #[cfg(target_arch = "wasm32")] pub async fn delete_document<T: Display>(&'a self, uid: T) -> Result<Progress<'a>, Error> { Ok(request::<(), ProgressJson>( &format!( "{}/indexes/{}/documents/{}", self.client.host, self.uid, uid ), self.client.apikey, Method::Delete, 202, ).await? .into_progress(self)) } /// Delete a selection of documents based on array of document id's. /// /// # Example /// /// ``` /// # use serde::{Serialize, Deserialize}; /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// # /// # #[derive(Serialize, Deserialize, Debug)] /// # struct Movie { /// # name: String, /// # description: String, /// # } /// # /// # // that trait is used by the sdk when the primary key is needed /// # impl Document for Movie { /// # type UIDType = String; /// # fn get_uid(&self) -> &Self::UIDType { /// # &self.name /// # } /// # } /// # /// # /// let client = Client::new("http://localhost:7700", ""); /// let mut movies = client.get_or_create("movies").unwrap(); /// /// // add some documents /// # movies.add_or_replace(vec![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.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).unwrap(); /// # std::thread::sleep(std::time::Duration::from_secs(1)); /// /// // delete some documents /// movies.delete_documents(vec!["Interstellar", "Unknown"]).unwrap(); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn delete_documents<T: Display + Serialize + std::fmt::Debug>( &mut self, uids: Vec<T>, ) -> Result<Progress, Error> { Ok(request::<Vec<T>, ProgressJson>( &format!( "{}/indexes/{}/documents/delete-batch", self.client.host, self.uid ), self.client.apikey, Method::Post(uids), 202, )? .into_progress(self)) } #[cfg(target_arch = "wasm32")] pub async fn delete_documents<T: Display + Serialize + std::fmt::Debug>( &'a self, uids: Vec<T>, ) -> Result<Progress<'a>, Error> { Ok(request::<Vec<T>, ProgressJson>( &format!( "{}/indexes/{}/documents/delete-batch", self.client.host, self.uid ), self.client.apikey, Method::Post(uids), 202, ).await? .into_progress(self)) } /// Get the [settings](../settings/struct.Settings.html) of the Index. /// /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, document::*}; /// let client = Client::new("http://localhost:7700", ""); /// let movie_index = client.get_or_create("movies").unwrap(); /// let settings = movie_index.get_settings().unwrap(); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn get_settings(&self) -> Result<Settings, Error> { Ok(request::<(), Settings>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), self.client.apikey, Method::Get, 200, )?) } #[cfg(target_arch = "wasm32")] pub async fn get_settings(&self) -> Result<Settings, Error> { Ok(request::<(), Settings>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), self.client.apikey, Method::Get, 200, ).await?) } /// Update the settings of the index. /// Updates in the settings are partial. This means that any parameters corresponding to a None value will be left unchanged. /// /// # Example /// /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, document::*, settings::Settings}; /// let client = Client::new("http://localhost:7700", ""); /// let mut movie_index = client.get_or_create("movies").unwrap(); /// /// let stop_words = vec![String::from("a"), String::from("the"), String::from("of")]; /// let settings = Settings::new() /// .with_stop_words(stop_words.clone()) /// .with_accept_new_fields(false); /// /// let progress = movie_index.set_settings(&settings).unwrap(); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn set_settings(&mut self, settings: &Settings) -> Result<Progress, Error> { Ok(request::<&Settings, ProgressJson>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), self.client.apikey, Method::Post(settings), 202, )? .into_progress(self)) } #[cfg(target_arch = "wasm32")] pub async fn set_settings(&'a self, settings: &Settings) -> Result<Progress<'a>, Error> { Ok(request::<&Settings, ProgressJson>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), self.client.apikey, Method::Post(settings), 202, ).await? .into_progress(self)) } /// Reset the settings of the index. /// All settings will be reset to their [default value](https://docs.meilisearch.com/references/settings.html#reset-settings). /// /// # Example /// /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, document::*, settings::Settings}; /// let client = Client::new("http://localhost:7700", ""); /// let mut movie_index = client.get_or_create("movies").unwrap(); /// /// let progress = movie_index.reset_settings().unwrap(); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn reset_settings(&mut self) -> Result<Progress, Error> { Ok(request::<(), ProgressJson>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), self.client.apikey, Method::Delete, 202, )? .into_progress(self)) } #[cfg(target_arch = "wasm32")] pub async fn reset_settings(&'a self) -> Result<Progress<'a>, Error> { Ok(request::<(), ProgressJson>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), self.client.apikey, Method::Delete, 202, ).await? .into_progress(self)) } /// Alias for the [update method](#method.update). #[cfg(not(target_arch = "wasm32"))] pub fn set_primary_key(&mut self, primary_key: &str) -> Result<(), Error> { self.update(primary_key) } #[cfg(target_arch = "wasm32")] pub async fn set_primary_key(&mut self, primary_key: &str) -> Result<(), Error> { self.update(primary_key).await } }