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
use crate::{
    client::Client, document::*, errors::Error, progress::*, request::*, search::*,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::json;
use std::{fmt::Display, collections::HashMap};

#[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::*};
/// # futures::executor::block_on(async move {
/// let client = Client::new("http://localhost:7700", "masterKey");
///
/// // get the index called movies or create it if it does not exist
/// let movies = client.get_or_create("movies").await.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.
    pub async fn update(&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::*};
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// # client.create_index("movies", None).await;
    ///
    /// // get the index named "movies" and delete it
    /// let movies = client.get_index("movies").await.unwrap();
    /// movies.delete().await.unwrap();
    /// # });
    /// ```
    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.\
    /// See also the [search method](#method.search).
    ///
    /// # 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
    ///     }
    /// }
    ///
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let mut movies = client.get_or_create("movies").await.unwrap();
    ///
    /// // add some documents
    /// # 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.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).await.unwrap();
    /// # std::thread::sleep(std::time::Duration::from_secs(1));
    ///
    /// let query = Query::new(&movies).with_query("Interstellar").with_limit(5).build();
    /// let results = movies.execute_query::<Movie>(&query).await.unwrap();
    /// # assert!(results.hits.len()>0);
    /// # });
    /// ```
    pub async fn execute_query<T: 'static + DeserializeOwned>(
        &self,
        query: &Query<'_>,
    ) -> Result<SearchResults<T>, Error> {
        Ok(request::<&Query, SearchResults<T>>(
            &format!(
                "{}/indexes/{}/search",
                self.client.host,
                self.uid
            ),
            self.client.apikey,
            Method::Post(query),
            200,
        ).await?)
    }

    /// Search for documents matching a specific query in the index.\
    /// See also the [execute_query method](#method.execute_query).
    ///
    /// # 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
    ///     }
    /// }
    ///
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// # client.delete_index("movies_search").await;
    /// let mut movies = client.get_or_create("movies").await.unwrap();
    ///
    /// // add some documents
    /// # 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.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).await.unwrap();
    /// # std::thread::sleep(std::time::Duration::from_secs(1));
    ///
    /// let results = movies.search()
    ///     .with_query("Interstellar")
    ///     .with_limit(5)
    ///     .execute::<Movie>()
    ///     .await
    ///     .unwrap();
    /// # assert!(results.hits.len()>0);
    /// # });
    /// ```
    pub fn search(&self) -> Query {
        Query::new(self)
    }

    /// 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::*};
    ///
    /// #[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
    ///    }
    /// }
    ///
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// # client.create_index("movies", None).await;
    /// let movies = client.get_index("movies").await.unwrap();
    /// # let mut movies = client.get_index("movies").await.unwrap();
    /// # 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();
    /// # 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")).await.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.")
    /// });
    /// # });
    /// ```
    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::*};
    ///
    /// #[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
    ///    }
    /// }
    ///
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// # client.create_index("movies", None).await;
    /// let movie_index = client.get_index("movies").await.unwrap();
    /// # let mut movie_index = client.get_index("movies").await.unwrap();
    ///
    /// # movie_index.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();
    /// # 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).await.unwrap();
    ///
    /// assert!(movies.len() > 0);
    /// # });
    /// ```
    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('&');
        }
        if let Some(limit) = limit {
            url.push_str("limit=");
            url.push_str(limit.to_string().as_str());
            url.push('&');
        }
        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;
    /// #[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
    ///    }
    /// }
    ///
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let mut movie_index = client.get_or_create("movies_add_or_replace").await.unwrap();
    ///
    /// let progress = movie_index.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.")
    ///     },
    ///     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")).await.unwrap();
    /// sleep(Duration::from_secs(1)); // MeiliSearch may take some time to execute the request
    /// # progress.get_status().await.unwrap();
    ///
    /// // retrieve movies (you have to put some movies in the index before)
    /// let movies = movie_index.get_documents::<Movie>(None, None, None).await.unwrap();
    /// assert!(movies.len() >= 3);
    /// # });
    /// ```
    pub async fn add_or_replace<T: Document>(
        &'a self,
        documents: &[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::<&[T], ProgressJson>(
                &url,
                self.client.apikey,
                Method::Post(documents),
                202,
            ).await?
            .into_progress(self),
        )
    }

    /// Alias for [add_or_replace](#method.add_or_replace).
    pub async fn add_documents<T: Document>(
        &'a self,
        documents: &[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;
    /// #[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
    ///    }
    /// }
    ///
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let mut movie_index = client.get_or_create("movies_add_or_update").await.unwrap();
    ///
    /// let progress = movie_index.add_or_update(&[
    ///     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")).await.unwrap();
    /// sleep(Duration::from_secs(1)); // MeiliSearch may take some time to execute the request
    /// # progress.get_status().await.unwrap();
    ///
    /// // retrieve movies (you have to put some movies in the index before)
    /// let movies = movie_index.get_documents::<Movie>(None, None, None).await.unwrap();
    /// assert!(movies.len() >= 3);
    /// # });
    /// ```
    pub async fn add_or_update<T: Document>(
        &'a self,
        documents: &[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::<&[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
    /// #    }
    /// # }
    /// #
    /// # futures::executor::block_on(async move {
    /// #
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let mut movie_index = client.get_or_create("movies").await.unwrap();
    ///
    /// // add some documents
    ///
    /// let progress = movie_index.delete_all_documents().await.unwrap();
    /// # std::thread::sleep(std::time::Duration::from_secs(1));
    /// # progress.get_status().await.unwrap();
    /// # let movies = movie_index.get_documents::<Movie>(None, None, None).await.unwrap();
    /// # assert_eq!(movies.len(), 0);
    /// # });
    /// ```
    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
    /// #    }
    /// # }
    /// #
    /// # futures::executor::block_on(async move {
    /// #
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let mut movies = client.get_or_create("movies").await.unwrap();
    ///
    /// # 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();
    /// # std::thread::sleep(std::time::Duration::from_secs(1));
    /// // add a document with id = Interstellar
    ///
    /// let progress = movies.delete_document("Interstellar").await.unwrap();
    /// # progress.get_status().await.unwrap();
    /// # });
    /// ```
    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
    /// #    }
    /// # }
    /// #
    /// # futures::executor::block_on(async move {
    /// #
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let mut movies = client.get_or_create("movies").await.unwrap();
    ///
    /// // add some documents
    /// # 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.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).await.unwrap();
    /// # std::thread::sleep(std::time::Duration::from_secs(1));
    ///
    /// // delete some documents
    /// let progress = movies.delete_documents(&["Interstellar", "Unknown"]).await.unwrap();
    /// # progress.get_status().await.unwrap();
    /// # });
    /// ```
    pub async fn delete_documents<T: Display + Serialize + std::fmt::Debug>(
        &'a self,
        uids: &[T],
    ) -> Result<Progress<'a>, Error> {
        Ok(request::<&[T], ProgressJson>(
            &format!(
                "{}/indexes/{}/documents/delete-batch",
                self.client.host, self.uid
            ),
            self.client.apikey,
            Method::Post(uids),
            202,
        ).await?
        .into_progress(self))
    }

    /// Alias for the [update method](#method.update).
    pub async fn set_primary_key(&self, primary_key: &str) -> Result<(), Error> {
        self.update(primary_key).await
    }

    /// Get the status of all updates in a given index.
    /// 
    /// # Example
    /// 
    /// ```
    /// # use serde::{Serialize, Deserialize};
    /// # use std::thread::sleep;
    /// # use std::time::Duration;
    /// # use meilisearch_sdk::{client::*, document, indexes::*};
    /// #
    /// # #[derive(Debug, Serialize, Deserialize, PartialEq)]
    /// # struct Document {
    /// #    id: usize,
    /// #    value: String,
    /// #    kind: String,
    /// # }
    /// # 
    /// # impl document::Document for Document {
    /// #    type UIDType = usize;
    /// #
    /// #    fn get_uid(&self) -> &Self::UIDType {
    /// #        &self.id
    /// #    }
    /// # }
    /// #
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let movies = client.get_or_create("movies_get_all_updates").await.unwrap();
    /// 
    /// # movies.add_documents(&[
    /// #     Document { id: 0, kind: "title".into(), value: "The Social Network".to_string() },
    /// #     Document { id: 1, kind: "title".into(), value: "Harry Potter and the Sorcerer's Stone".to_string() },
    /// # ], None).await.unwrap();
    /// # sleep(Duration::from_secs(1));
    /// 
    /// # movies.add_documents(&[
    /// #    Document { id: 0, kind: "title".into(), value: "Harry Potter and the Chamber of Secrets".to_string() },
    /// #    Document { id: 1, kind: "title".into(), value: "Harry Potter and the Prisoner of Azkaban".to_string() },
    /// # ], None).await.unwrap();
    /// # sleep(Duration::from_secs(1));
    /// 
    /// let status = movies.get_all_updates().await.unwrap();
    /// assert_eq!(status.len(), 2);
    /// # client.delete_index("movies_get_all_updates").await.unwrap();
    /// # });
    /// ```
    pub async fn get_all_updates(&self) -> Result<Vec<UpdateStatus>, Error> {
        request::<(), Vec<UpdateStatus>>(
            &format!(
                "{}/indexes/{}/updates",
                self.client.host, self.uid
            ),
            self.client.apikey,
            Method::Get,
            200,
        )
        .await
    }

    /// Get stats of an index.
    ///
    /// # Example
    ///
    /// ```
    /// # use meilisearch_sdk::{client::*, indexes::*};
    /// #
    /// # futures::executor::block_on(async move {
    /// let client = Client::new("http://localhost:7700", "masterKey");
    /// let movies = client.get_or_create("movies").await.unwrap();
    ///
    /// let stats = movies.get_stats().await.unwrap();
    /// # });
    /// ```
    pub async fn get_stats(&self) -> Result<IndexStats, Error> {
        request::<serde_json::Value, IndexStats>(
            &format!("{}/indexes/{}/stats", self.client.host, self.uid),
            self.client.apikey,
            Method::Get,
            200,
        ).await
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexStats {
    pub number_of_documents: usize,
    pub is_indexing: bool,
    pub fields_distribution: HashMap<String, usize>,
}

#[cfg(test)]
mod tests {
    use crate::{client::*};
    use futures_await_test::async_test;

    #[async_test]
    async fn test_get_all_updates_no_docs() {
        let client = Client::new("http://localhost:7700", "masterKey");
        let uid = "test_get_all_updates_no_docs";

        let index = client.get_or_create(uid).await.unwrap();
        let status = index.get_all_updates().await.unwrap();
        client.delete_index(uid).await.unwrap();

        assert_eq!(status.len(), 0);
    }
}