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
use reqwest::Url;
use std::error::Error;
use std::sync::Arc;
use crate::collections::{
batch::{BatchAddObjects, BatchAddReferencesResponse, BatchDeleteRequest, BatchDeleteResponse},
error::BatchError,
objects::{ConsistencyLevel, MultiObjects, References},
};
/// All batch related endpoints and functionality described in
/// [Weaviate meta API documentation](https://weaviate.io/developers/weaviate/api/rest/batch)
#[derive(Debug)]
pub struct Batch {
endpoint: Url,
client: Arc<reqwest::Client>,
}
impl Batch {
pub(super) fn new(url: &Url, client: Arc<reqwest::Client>) -> Result<Self, Box<dyn Error>> {
let endpoint = url.join("/v1/batch/")?;
Ok(Batch { endpoint, client })
}
/// Batch add objects.
///
/// # Parameters
/// - objects: the objects to add
/// - consistency_level: the consistency level to use
///
/// # Example
/// ```rust
/// use uuid::Uuid;
/// use weaviate_community::WeaviateClient;
/// use weaviate_community::collections::objects::{Object, MultiObjects, ConsistencyLevel};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = WeaviateClient::builder("http://localhost:8080").build()?;
///
/// let author_uuid = Uuid::parse_str("36ddd591-2dee-4e7e-a3cc-eb86d30a4303").unwrap();
/// let article_a_uuid = Uuid::parse_str("6bb06a43-e7f0-393e-9ecf-3c0f4e129064").unwrap();
/// let article_b_uuid = Uuid::parse_str("b72912b9-e5d7-304e-a654-66dc63c55b32").unwrap();
///
/// let article_a = Object::builder("Article", serde_json::json!({}))
/// .with_id(article_a_uuid.clone())
/// .build();
///
/// let article_b = Object::builder("Article", serde_json::json!({}))
/// .with_id(article_b_uuid.clone())
/// .build();
///
/// let author = Object::builder("Author", serde_json::json!({}))
/// .with_id(author_uuid.clone())
/// .build();
///
/// let res = client.batch.objects_batch_add(
/// MultiObjects::new(vec![article_a, article_b, author]), Some(ConsistencyLevel::ALL)
/// ).await;
///
/// Ok(())
/// }
/// ```
pub async fn objects_batch_add(
&self,
objects: MultiObjects,
consistency_level: Option<ConsistencyLevel>,
) -> Result<BatchAddObjects, Box<dyn Error>> {
let mut endpoint = self.endpoint.join("objects")?;
if let Some(x) = consistency_level {
endpoint
.query_pairs_mut()
.append_pair("consistency_level", x.value());
}
let payload = serde_json::to_value(&objects)?;
let res = self.client.post(endpoint).json(&payload).send().await?;
match res.status() {
reqwest::StatusCode::OK => {
let res: BatchAddObjects = res.json().await?;
Ok(res)
}
_ => Err(Box::new(BatchError(format!(
"status code {} received.",
res.status()
)))),
}
}
/// Batch delete objects.
///
/// # Parameters
/// - request_body: the config to use for deletion
/// - consistency_level: the consistency level to use
///
/// # Example
/// ```rust
/// use uuid::Uuid;
/// use weaviate_community::WeaviateClient;
/// use weaviate_community::collections::objects::{Object, MultiObjects, ConsistencyLevel};
/// use weaviate_community::collections::batch::{BatchDeleteRequest, MatchConfig};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = WeaviateClient::builder("http://localhost:8080").build()?;
/// let req = BatchDeleteRequest::builder(
/// MatchConfig::new(
/// "Article",
/// serde_json::json!({
/// "operator": "Like",
/// "path": ["id"],
/// "valueText": "*4*",
/// })
/// )
/// ).build();
///
/// let res = client.batch.objects_batch_delete(req, Some(ConsistencyLevel::ALL)).await;
///
/// Ok(())
/// }
/// ```
pub async fn objects_batch_delete(
&self,
request_body: BatchDeleteRequest,
consistency_level: Option<ConsistencyLevel>,
) -> Result<BatchDeleteResponse, Box<dyn Error>> {
let mut endpoint = self.endpoint.join("objects")?;
if let Some(x) = consistency_level {
endpoint
.query_pairs_mut()
.append_pair("consistency_level", x.value());
}
let payload = serde_json::to_value(&request_body)?;
let res = self.client.delete(endpoint).json(&payload).send().await?;
match res.status() {
reqwest::StatusCode::OK => {
let res: BatchDeleteResponse = res.json().await?;
Ok(res)
}
_ => Err(Box::new(BatchError(format!(
"status code {} received.",
res.status()
)))),
}
}
/// Batch add references.
///
/// Note that the consistency_level and tenant_name in the `Reference` items contained within
/// the `References` input bare no effect on this method and will be ignored.
///
/// # Parameters
/// - references: the references to add
/// - consistency_level: the consistency level to use
///
/// # Example
/// ```rust
/// use uuid::Uuid;
/// use weaviate_community::WeaviateClient;
/// use weaviate_community::collections::objects::{Reference, References, ConsistencyLevel};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = WeaviateClient::builder("http://localhost:8080").build()?;
///
/// let author_uuid = Uuid::parse_str("36ddd591-2dee-4e7e-a3cc-eb86d30a4303").unwrap();
/// let article_a_uuid = Uuid::parse_str("6bb06a43-e7f0-393e-9ecf-3c0f4e129064").unwrap();
/// let article_b_uuid = Uuid::parse_str("b72912b9-e5d7-304e-a654-66dc63c55b32").unwrap();
///
/// let references = References::new(vec![
/// Reference::new(
/// "Author",
/// &author_uuid,
/// "wroteArticles",
/// "Article",
/// &article_a_uuid,
/// ),
/// Reference::new(
/// "Author",
/// &author_uuid,
/// "wroteArticles",
/// "Article",
/// &article_b_uuid,
/// ),
/// ]);
///
/// let res = client.batch.references_batch_add(
/// references,
/// Some(ConsistencyLevel::ALL)
/// ).await;
///
/// Ok(())
/// }
/// ```
pub async fn references_batch_add(
&self,
references: References,
consistency_level: Option<ConsistencyLevel>,
) -> Result<BatchAddReferencesResponse, Box<dyn Error>> {
let mut converted: Vec<serde_json::Value> = Vec::new();
for reference in references.0 {
let new_ref = serde_json::json!({
"from": format!(
"weaviate://localhost/{}/{}/{}",
reference.from_class_name,
reference.from_uuid,
reference.from_property_name
),
"to": format!(
"weaviate://localhost/{}/{}",
reference.to_class_name,
reference.to_uuid
),
});
converted.push(new_ref);
}
let payload = serde_json::json!(converted);
let mut endpoint = self.endpoint.join("references")?;
if let Some(cl) = consistency_level {
endpoint
.query_pairs_mut()
.append_pair("consistency_level", &cl.value());
}
let res = self.client.post(endpoint).json(&payload).send().await?;
match res.status() {
reqwest::StatusCode::OK => {
let res: BatchAddReferencesResponse = res.json().await?;
Ok(res)
}
_ => Err(Box::new(BatchError(format!(
"status code {} received.",
res.status()
)))),
}
}
}
#[cfg(test)]
mod tests {
use uuid::Uuid;
use crate::{
collections::objects::{MultiObjects, Object},
collections::{
batch::{
BatchAddObject, BatchDeleteRequest, BatchDeleteResponse, BatchDeleteResult,
GeneralStatus, MatchConfig, ResultStatus,
},
objects::{Reference, References},
},
WeaviateClient,
};
fn get_test_harness() -> (mockito::ServerGuard, WeaviateClient) {
let mock_server = mockito::Server::new();
let mut host = "http://".to_string();
host.push_str(&mock_server.host_with_port());
let client = WeaviateClient::builder(&host).build().unwrap();
(mock_server, client)
}
fn test_create_objects() -> MultiObjects {
let properties = serde_json::json!({
"name": "test",
"number": 123,
});
MultiObjects {
objects: vec![Object {
class: "Test".into(),
properties,
id: Some(Uuid::new_v4()),
vector: None,
tenant: None,
creation_time_unix: None,
last_update_time_unix: None,
vector_weights: None,
additional: None
}],
}
}
fn test_batch_add_object_response() -> String {
let properties = serde_json::json!({
"name": "test",
"number": 123,
});
serde_json::to_string(&vec![BatchAddObject {
class: "Test".into(),
properties,
id: None,
vector: None,
tenant: None,
creation_time_unix: None,
last_update_time_unix: None,
vector_weights: None,
result: ResultStatus {
status: GeneralStatus::SUCCESS,
},
}])
.unwrap()
}
fn test_delete_objects() -> BatchDeleteRequest {
// this will eventually be defined with the graphql stuff later on
let map = serde_json::json!({
"operator": "NotEqual",
"path": ["name"],
"valueText": "aaa"
});
BatchDeleteRequest::builder(MatchConfig::new("Test", map)).build()
}
fn test_delete_response() -> BatchDeleteResponse {
let map = serde_json::json!({
"operator": "NotEqual",
"path": ["name"],
"valueText": "aaa"
});
BatchDeleteResponse {
matches: MatchConfig::new("Test", map),
output: None,
dry_run: None,
results: BatchDeleteResult {
matches: 0,
limit: 1,
successful: 1,
failed: 0,
objects: None,
},
}
}
fn test_references() -> References {
let uuid = Uuid::parse_str("36ddd591-2dee-4e7e-a3cc-eb86d30a4303").unwrap();
let uuid2 = Uuid::parse_str("6bb06a43-e7f0-393e-9ecf-3c0f4e129064").unwrap();
let uuid3 = Uuid::parse_str("b72912b9-e5d7-304e-a654-66dc63c55b32").unwrap();
References::new(vec![
Reference::new("Test", &uuid, "testProp", "Other", &uuid2),
Reference::new("Test", &uuid, "testProp", "Other", &uuid3),
])
}
fn test_add_references_response() -> String {
serde_json::to_string(&serde_json::json!([{
"result": {
"errors": {
"error": [
{
"message": "test"
}
]
},
"status": "FAILED"
}
}]))
.unwrap()
}
fn mock_post(
server: &mut mockito::ServerGuard,
endpoint: &str,
status_code: usize,
body: &str,
) -> mockito::Mock {
server
.mock("POST", endpoint)
.with_status(status_code)
.with_header("content-type", "application/json")
.with_body(body)
.create()
}
fn mock_delete(
server: &mut mockito::ServerGuard,
endpoint: &str,
status_code: usize,
body: &str,
) -> mockito::Mock {
server
.mock("DELETE", endpoint)
.with_status(status_code)
.with_header("content-type", "application/json")
.with_body(body)
.create()
}
#[tokio::test]
async fn test_objects_batch_add_ok() {
let objects = test_create_objects();
let res_str = test_batch_add_object_response();
let (mut mock_server, client) = get_test_harness();
let mock = mock_post(&mut mock_server, "/v1/batch/objects", 200, &res_str);
let res = client.batch.objects_batch_add(objects, None).await;
mock.assert();
assert!(res.is_ok());
}
#[tokio::test]
async fn test_objects_batch_add_err() {
let objects = test_create_objects();
let (mut mock_server, client) = get_test_harness();
let mock = mock_post(&mut mock_server, "/v1/batch/objects", 404, "");
let res = client.batch.objects_batch_add(objects, None).await;
mock.assert();
assert!(res.is_err());
}
#[tokio::test]
async fn test_objects_batch_delete_ok() {
let req = test_delete_objects();
let out = test_delete_response();
let res_str = serde_json::to_string(&out).unwrap();
let (mut mock_server, client) = get_test_harness();
let mock = mock_delete(&mut mock_server, "/v1/batch/objects", 200, &res_str);
let res = client.batch.objects_batch_delete(req, None).await;
mock.assert();
assert!(res.is_ok());
}
#[tokio::test]
async fn test_objects_batch_delete_err() {
let req = test_delete_objects();
let (mut mock_server, client) = get_test_harness();
let mock = mock_delete(&mut mock_server, "/v1/batch/objects", 401, "");
let res = client.batch.objects_batch_delete(req, None).await;
mock.assert();
assert!(res.is_err());
}
#[tokio::test]
async fn test_references_batch_add_ok() {
let refs = test_references();
let res_str = test_add_references_response();
let (mut mock_server, client) = get_test_harness();
let mock = mock_post(&mut mock_server, "/v1/batch/references", 200, &res_str);
let res = client.batch.references_batch_add(refs, None).await;
mock.assert();
assert!(res.is_ok());
}
#[tokio::test]
async fn test_references_batch_add_err() {
let refs = test_references();
let (mut mock_server, client) = get_test_harness();
let mock = mock_post(&mut mock_server, "/v1/batch/references", 500, "");
let res = client.batch.references_batch_add(refs, None).await;
mock.assert();
assert!(res.is_err());
}
}