Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions .code-samples.meilisearch.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -109,27 +109,27 @@ get_all_tasks_1: |-
.await
.unwrap();
get_all_tasks_filtering_1: |-
let mut query = TasksQuery::new(&client)
.with_index_uid(["movies"])
let mut query = TasksSearchQuery::new(&client)
.with_index_uids(["movies"])
.execute()
.await
.unwrap();
get_all_tasks_filtering_2: |-
let mut query = TasksQuery::new(&client)
.with_status(["succeeded", "failed"])
.with_type(["documentAdditionOrUpdate"])
let mut query = TasksSearchQuery::new(&client)
.with_statuses(["succeeded", "failed"])
.with_types(["documentAdditionOrUpdate"])
.execute()
.await
.unwrap();
get_all_tasks_paginating_1: |-
let mut query = TasksQuery::new(&client)
let mut query = TasksSearchQuery::new(&client)
.with_limit(2)
.with_from(10)
.execute()
.await
.unwrap();
get_all_tasks_paginating_2: |-
let mut query = TasksQuery::new(&client)
let mut query = TasksSearchQuery::new(&client)
.with_limit(2)
.from(8)
.execute()
Expand Down Expand Up @@ -828,7 +828,7 @@ primary_field_guide_add_document_primary_key: |-
getting_started_add_documents_md: |-
```toml
[dependencies]
meilisearch-sdk = "0.20"
meilisearch-sdk = "0.21"
# futures: because we want to block on futures
futures = "0.3"
# serde: required if you are going to use documents
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "meilisearch-sdk"
version = "0.20.1"
version = "0.21.0"
authors = ["Mubelotix <[email protected]>"]
edition = "2018"
description = "Rust wrapper for the Meilisearch API. Meilisearch is a powerful, fast, open-source, easy to use and deploy search engine."
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ To use `meilisearch-sdk`, add this to your `Cargo.toml`:

```toml
[dependencies]
meilisearch-sdk = "0.20.1"
meilisearch-sdk = "0.21.0"
```

The following optional dependencies may also be useful:
Expand Down Expand Up @@ -244,7 +244,7 @@ WARNING: `meilisearch-sdk` will panic if no Window is available (ex: Web extensi

## 🤖 Compatibility with Meilisearch

This package only guarantees the compatibility with the [version v0.29.0 of Meilisearch](https://github.com/meilisearch/meilisearch/releases/tag/v0.29.0).
This package only guarantees the compatibility with the [version v0.30.0 of Meilisearch](https://github.com/meilisearch/meilisearch/releases/tag/v0.30.0).

## ⚙️ Contributing

Expand Down
4 changes: 2 additions & 2 deletions README.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ To use `meilisearch-sdk`, add this to your `Cargo.toml`:

```toml
[dependencies]
meilisearch-sdk = "0.20.1"
meilisearch-sdk = "0.21.0"
```

The following optional dependencies may also be useful:
Expand Down Expand Up @@ -99,7 +99,7 @@ WARNING: `meilisearch-sdk` will panic if no Window is available (ex: Web extensi

## 🤖 Compatibility with Meilisearch

This package only guarantees the compatibility with the [version v0.29.0 of Meilisearch](https://github.com/meilisearch/meilisearch/releases/tag/v0.29.0).
This package only guarantees the compatibility with the [version v0.30.0 of Meilisearch](https://github.com/meilisearch/meilisearch/releases/tag/v0.30.0).

## ⚙️ Contributing

Expand Down
202 changes: 190 additions & 12 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::{collections::HashMap, time::Duration};

use serde::Deserialize;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{collections::HashMap, time::Duration};
use time::OffsetDateTime;

use crate::{
Expand All @@ -10,7 +9,7 @@ use crate::{
key::{Key, KeyBuilder, KeyUpdater, KeysQuery, KeysResults},
request::*,
task_info::TaskInfo,
tasks::{Task, TasksQuery, TasksResults},
tasks::{Task, TasksCancelQuery, TasksDeleteQuery, TasksResults, TasksSearchQuery},
utils::async_sleep,
};

Expand All @@ -21,6 +20,11 @@ pub struct Client {
pub(crate) api_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwapIndexes {
pub indexes: (String, String),
}

impl Client {
/// Create a client using the specified server.
/// Don't put a '/' at the end of the host.
Expand Down Expand Up @@ -331,6 +335,56 @@ impl Client {
self.list_all_indexes_raw_with(indexes_query).await
}

/// Swaps a list of two [Index]'es.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*};
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # futures::executor::block_on(async move {
/// // Create the client
/// let client = Client::new(MEILISEARCH_URL, MEILISEARCH_API_KEY);
///
/// let task_index_1 = client.create_index("swap_index_1", None).await.unwrap();
/// let task_index_2 = client.create_index("swap_index_2", None).await.unwrap();
///
/// // Wait for the task to complete
/// task_index_2.wait_for_completion(&client, None, None).await.unwrap();
///
/// let task = client
/// .swap_indexes([&SwapIndexes {
/// indexes: (
/// "swap_index_1".to_string(),
/// "swap_index_2".to_string(),
/// ),
/// }])
/// .await
/// .unwrap();
///
/// # client.index("swap_index_1").delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # client.index("swap_index_2").delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
/// ```
pub async fn swap_indexes(
&self,
indexes: impl IntoIterator<Item = &SwapIndexes>,
) -> Result<TaskInfo, Error> {
request::<(), Vec<&SwapIndexes>, TaskInfo>(
&format!("{}/swap-indexes", self.host),
&self.api_key,
Method::Post {
query: (),
body: indexes.into_iter().collect(),
},
202,
)
.await
}

/// Get stats of all indexes.
///
/// # Example
Expand Down Expand Up @@ -756,16 +810,16 @@ impl Client {
/// # futures::executor::block_on(async move {
/// # let client = client::Client::new(MEILISEARCH_URL, MEILISEARCH_API_KEY);
///
/// let mut query = tasks::TasksQuery::new(&client);
/// query.with_index_uid(["get_tasks_with"]);
/// let mut query = tasks::TasksSearchQuery::new(&client);
/// query.with_index_uids(["get_tasks_with"]);
/// let tasks = client.get_tasks_with(&query).await.unwrap();
/// # });
/// ```
pub async fn get_tasks_with(
&self,
tasks_query: &TasksQuery<'_>,
tasks_query: &TasksSearchQuery<'_>,
) -> Result<TasksResults, Error> {
let tasks = request::<&TasksQuery, (), TasksResults>(
let tasks = request::<&TasksSearchQuery, (), TasksResults>(
&format!("{}/tasks", self.host),
&self.api_key,
Method::Get { query: tasks_query },
Expand All @@ -776,6 +830,77 @@ impl Client {
Ok(tasks)
}

/// Cancel tasks with filters [TasksCancelQuery]
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::*;
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # futures::executor::block_on(async move {
/// # let client = client::Client::new(MEILISEARCH_URL, MEILISEARCH_API_KEY);
///
/// let mut query = tasks::TasksCancelQuery::new(&client);
/// query.with_index_uids(["movies"]);
///
/// let res = client.cancel_tasks_with(&query).await.unwrap();
/// # });
/// ```
pub async fn cancel_tasks_with(
&self,
filters: &TasksCancelQuery<'_>,
) -> Result<TaskInfo, Error> {
let tasks = request::<&TasksCancelQuery, (), TaskInfo>(
&format!("{}/tasks/cancel", self.host),
&self.api_key,
Method::Post {
query: filters,
body: (),
},
200,
)
.await?;

Ok(tasks)
}

/// Delete tasks with filters [TasksDeleteQuery]
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::*;
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # futures::executor::block_on(async move {
/// # let client = client::Client::new(MEILISEARCH_URL, MEILISEARCH_API_KEY);
///
/// let mut query = tasks::TasksDeleteQuery::new(&client);
/// query.with_index_uids(["movies"]);
///
/// let res = client.delete_tasks_with(&query).await.unwrap();
/// # });
/// ```
pub async fn delete_tasks_with(
&self,
filters: &TasksDeleteQuery<'_>,
) -> Result<TaskInfo, Error> {
let tasks = request::<&TasksDeleteQuery, (), TaskInfo>(
&format!("{}/tasks", self.host),
&self.api_key,
Method::Delete { query: filters },
200,
)
.await?;

Ok(tasks)
}

/// Get all tasks from the server.
///
/// # Example
Expand All @@ -791,7 +916,6 @@ impl Client {
/// let tasks = client.get_tasks().await.unwrap();
///
/// # assert!(tasks.results.len() > 0);
/// # client.index("get_tasks").delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
/// ```
pub async fn get_tasks(&self) -> Result<TasksResults, Error> {
Expand Down Expand Up @@ -894,8 +1018,62 @@ mod tests {
use crate::{
client::*,
key::{Action, KeyBuilder},
tasks::TasksSearchQuery,
};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Document {
id: String,
}

#[meilisearch_test]
async fn test_swapping_two_indexes(client: Client) {
let index_1 = client.index("test_swapping_two_indexes_1");
let index_2 = client.index("test_swapping_two_indexes_2");

let t0 = index_1
.add_documents(
&[Document {
id: "1".to_string(),
}],
None,
)
.await
.unwrap();

index_2
.add_documents(
&[Document {
id: "2".to_string(),
}],
None,
)
.await
.unwrap();

t0.wait_for_completion(&client, None, None).await.unwrap();

let task = client
.swap_indexes([&SwapIndexes {
indexes: (
"test_swapping_two_indexes_1".to_string(),
"test_swapping_two_indexes_2".to_string(),
),
}])
.await
.unwrap();
task.wait_for_completion(&client, None, None).await.unwrap();

let document = index_1.get_document("2").await.unwrap();

assert_eq!(
Document {
id: "2".to_string()
},
document
);
}

#[meilisearch_test]
async fn test_methods_has_qualified_version_as_header() {
let mock_server_url = &mockito::server_url();
Expand Down Expand Up @@ -971,15 +1149,15 @@ mod tests {
#[meilisearch_test]
async fn test_get_tasks(client: Client) {
let tasks = client.get_tasks().await.unwrap();
assert!(tasks.results.len() >= 2);
assert!(tasks.limit == 20);
}

#[meilisearch_test]
async fn test_get_tasks_with_params(client: Client) {
let query = TasksQuery::new(&client);
let query = TasksSearchQuery::new(&client);
let tasks = client.get_tasks_with(&query).await.unwrap();

assert!(tasks.results.len() >= 2);
assert!(tasks.limit == 20);
}

#[meilisearch_test]
Expand Down
7 changes: 7 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ pub enum ErrorCode {
MissingAuthorizationHeader,
TaskNotFound,
DumpNotFound,
MssingMasterKey,
NoSpaceLeftOnDevice,
PayloadTooLarge,
UnretrievableDocument,
Expand All @@ -156,6 +157,12 @@ pub enum ErrorCode {
InvalidApiKeyIndexes,
InvalidApiKeyExpiresAt,
ApiKeyNotFound,
InvalidTaskTypesFilter,
InvalidTaskStatusesFilter,
InvalidTaskCanceledByFilter,
InvalidTaskUidsFilter,
InvalidTaskDateFilter,
MissingTaskFilters,

/// That's unexpected. Please open a GitHub issue after ensuring you are
/// using the supported version of the Meilisearch server.
Expand Down
Loading