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
//! Data operations (nodes and relationships)
use crate::client::NexusClient;
use crate::error::{NexusError, Result};
use crate::models::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Create node request
#[derive(Debug, Clone, Serialize)]
pub struct CreateNodeRequest {
/// Node labels
pub labels: Vec<String>,
/// Node properties
#[serde(default)]
pub properties: HashMap<String, Value>,
}
/// Create node response
#[derive(Debug, Clone, Deserialize)]
pub struct CreateNodeResponse {
/// Created node ID
pub node_id: u64,
/// Success message
pub message: String,
/// Error message if any
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Get node response
#[derive(Debug, Clone, Deserialize)]
pub struct GetNodeResponse {
/// Node data
pub node: Option<Node>,
/// Success message
pub message: String,
/// Error message if any
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Update node request
#[derive(Debug, Clone, Serialize)]
pub struct UpdateNodeRequest {
/// Node ID
pub node_id: u64,
/// New properties (will replace existing)
pub properties: HashMap<String, Value>,
}
/// Update node response
#[derive(Debug, Clone, Deserialize)]
pub struct UpdateNodeResponse {
/// Success message
pub message: String,
/// Error message if any
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Delete node response
#[derive(Debug, Clone, Deserialize)]
pub struct DeleteNodeResponse {
/// Success message
pub message: String,
/// Error message if any
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Create relationship request
#[derive(Debug, Clone, Serialize)]
pub struct CreateRelRequest {
/// Source node ID
pub source_id: u64,
/// Target node ID
pub target_id: u64,
/// Relationship type
pub rel_type: String,
/// Relationship properties
#[serde(default)]
pub properties: HashMap<String, Value>,
}
/// Create relationship response
#[derive(Debug, Clone, Deserialize)]
pub struct CreateRelResponse {
/// Relationship ID
pub rel_id: u64,
/// Success message
pub message: String,
/// Error message if any
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Update relationship request
#[derive(Debug, Clone, Serialize)]
pub struct UpdateRelRequest {
/// Relationship ID
pub rel_id: u64,
/// New properties (will replace existing)
pub properties: HashMap<String, Value>,
}
/// Update relationship response
#[derive(Debug, Clone, Deserialize)]
pub struct UpdateRelResponse {
/// Success message
pub message: String,
/// Error message if any
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Delete relationship response
#[derive(Debug, Clone, Deserialize)]
pub struct DeleteRelResponse {
/// Success message
pub message: String,
/// Error message if any
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
impl NexusClient {
/// Create a new node
///
/// # Arguments
///
/// * `labels` - Node labels
/// * `properties` - Node properties
///
/// # Example
///
/// ```no_run
/// # use nexus_sdk::{NexusClient, Value};
/// # use std::collections::HashMap;
/// # #[tokio::main]
/// # async fn main() -> Result<(), nexus_sdk::NexusError> {
/// # let client = NexusClient::new("http://localhost:15474")?;
/// let mut properties = HashMap::new();
/// properties.insert("name".to_string(), Value::String("Alice".to_string()));
/// let response = client.create_node(vec!["Person".to_string()], properties).await?;
/// tracing::info!("Created node with ID: {}", response.node_id);
/// # Ok(())
/// # }
/// ```
pub async fn create_node(
&self,
labels: Vec<String>,
properties: HashMap<String, Value>,
) -> Result<CreateNodeResponse> {
let request = CreateNodeRequest { labels, properties };
let url = self.get_base_url().join("/data/nodes")?;
let mut request_builder = self.get_client().post(url).json(&request);
request_builder = self.add_auth_headers(request_builder)?;
let response = self.execute_with_retry(request_builder).await?;
let status = response.status();
if status.is_success() {
let result: CreateNodeResponse = response.json().await?;
Ok(result)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(NexusError::Api {
message: error_text,
status: status.as_u16(),
})
}
}
/// Get a node by ID
///
/// # Arguments
///
/// * `node_id` - ID of the node to retrieve
///
/// # Example
///
/// ```no_run
/// # use nexus_sdk::NexusClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), nexus_sdk::NexusError> {
/// # let client = NexusClient::new("http://localhost:15474")?;
/// let response = client.get_node(0).await?; // Replace 0 with an actual node ID
/// if let Some(node) = response.node {
/// tracing::info!("Retrieved node: {:?}", node);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_node(&self, node_id: u64) -> Result<GetNodeResponse> {
let url = self
.get_base_url()
.join(&format!("/data/nodes?id={}", node_id))?;
let mut request_builder = self.get_client().get(url);
request_builder = self.add_auth_headers(request_builder)?;
let response = self.execute_with_retry(request_builder).await?;
let status = response.status();
if status.is_success() {
let result: GetNodeResponse = response.json().await?;
Ok(result)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(NexusError::Api {
message: error_text,
status: status.as_u16(),
})
}
}
/// Update an existing node
///
/// # Arguments
///
/// * `node_id` - ID of the node to update
/// * `properties` - New properties for the node
///
/// # Example
///
/// ```no_run
/// # use nexus_sdk::{NexusClient, Value};
/// # use std::collections::HashMap;
/// # #[tokio::main]
/// # async fn main() -> Result<(), nexus_sdk::NexusError> {
/// # let client = NexusClient::new("http://localhost:15474")?;
/// let mut properties = HashMap::new();
/// properties.insert("name".to_string(), Value::String("Bob".to_string()));
/// let response = client.update_node(0, properties).await?; // Replace 0 with an actual node ID
/// tracing::info!("Update node result: {}", response.message);
/// # Ok(())
/// # }
/// ```
pub async fn update_node(
&self,
node_id: u64,
properties: HashMap<String, Value>,
) -> Result<UpdateNodeResponse> {
let request = UpdateNodeRequest {
node_id,
properties,
};
let url = self.get_base_url().join("/data/nodes")?;
let mut request_builder = self.get_client().put(url).json(&request);
request_builder = self.add_auth_headers(request_builder)?;
let response = self.execute_with_retry(request_builder).await?;
let status = response.status();
if status.is_success() {
let result: UpdateNodeResponse = response.json().await?;
Ok(result)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(NexusError::Api {
message: error_text,
status: status.as_u16(),
})
}
}
/// Delete a node by ID
///
/// # Arguments
///
/// * `node_id` - ID of the node to delete
///
/// # Example
///
/// ```no_run
/// # use nexus_sdk::NexusClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), nexus_sdk::NexusError> {
/// # let client = NexusClient::new("http://localhost:15474")?;
/// let response = client.delete_node(0).await?; // Replace 0 with an actual node ID
/// tracing::info!("Delete result: {}", response.message);
/// # Ok(())
/// # }
/// ```
pub async fn delete_node(&self, node_id: u64) -> Result<DeleteNodeResponse> {
let url = self
.get_base_url()
.join(&format!("/data/nodes?id={}", node_id))?;
let mut request_builder = self.get_client().delete(url);
request_builder = self.add_auth_headers(request_builder)?;
let response = self.execute_with_retry(request_builder).await?;
let status = response.status();
if status.is_success() {
let result: DeleteNodeResponse = response.json().await?;
Ok(result)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(NexusError::Api {
message: error_text,
status: status.as_u16(),
})
}
}
/// Create a new relationship
///
/// # Arguments
///
/// * `source_id` - ID of the source node
/// * `target_id` - ID of the target node
/// * `rel_type` - Type of the relationship
/// * `properties` - Optional relationship properties
///
/// # Example
///
/// ```no_run
/// # use nexus_sdk::{NexusClient, Value};
/// # use std::collections::HashMap;
/// # #[tokio::main]
/// # async fn main() -> Result<(), nexus_sdk::NexusError> {
/// # let client = NexusClient::new("http://localhost:15474")?;
/// let mut properties = HashMap::new();
/// properties.insert("weight".to_string(), Value::Float(1.5));
/// let response = client.create_relationship(1, 2, "KNOWS".to_string(), properties).await?;
/// tracing::info!("Created relationship with ID: {}", response.rel_id);
/// # Ok(())
/// # }
/// ```
pub async fn create_relationship(
&self,
source_id: u64,
target_id: u64,
rel_type: String,
properties: HashMap<String, Value>,
) -> Result<CreateRelResponse> {
let request = CreateRelRequest {
source_id,
target_id,
rel_type,
properties,
};
let url = self.get_base_url().join("/data/relationships")?;
let mut request_builder = self.get_client().post(url).json(&request);
request_builder = self.add_auth_headers(request_builder)?;
let response = self.execute_with_retry(request_builder).await?;
let status = response.status();
if status.is_success() {
let result: CreateRelResponse = response.json().await?;
Ok(result)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(NexusError::Api {
message: error_text,
status: status.as_u16(),
})
}
}
/// Update an existing relationship using Cypher
///
/// # Arguments
///
/// * `rel_id` - ID of the relationship to update
/// * `properties` - New properties for the relationship
///
/// # Example
///
/// ```no_run
/// # use nexus_sdk::{NexusClient, Value};
/// # use std::collections::HashMap;
/// # #[tokio::main]
/// # async fn main() -> Result<(), nexus_sdk::NexusError> {
/// # let client = NexusClient::new("http://localhost:15474")?;
/// let mut properties = HashMap::new();
/// properties.insert("weight".to_string(), Value::Float(2.0));
/// let response = client.update_relationship(1, properties).await?;
/// tracing::info!("Update relationship result: {}", response.message);
/// # Ok(())
/// # }
/// ```
pub async fn update_relationship(
&self,
rel_id: u64,
properties: HashMap<String, Value>,
) -> Result<UpdateRelResponse> {
// Use Cypher SET to update relationship properties
let mut props_str = Vec::new();
let mut params = HashMap::new();
for (key, value) in properties {
let param_name = format!("prop_{}", key.replace('-', "_"));
props_str.push(format!("r.{} = ${}", key, param_name));
params.insert(param_name, value);
}
let query = format!(
"MATCH ()-[r]->() WHERE id(r) = $rel_id SET {} RETURN r",
props_str.join(", ")
);
params.insert("rel_id".to_string(), Value::Int(rel_id as i64));
let _result = self.execute_cypher(&query, Some(params)).await?;
Ok(UpdateRelResponse {
message: "Relationship updated successfully".to_string(),
error: None,
})
}
/// Delete a relationship using Cypher
///
/// # Arguments
///
/// * `rel_id` - ID of the relationship to delete
///
/// # Example
///
/// ```no_run
/// # use nexus_sdk::NexusClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), nexus_sdk::NexusError> {
/// # let client = NexusClient::new("http://localhost:15474")?;
/// let response = client.delete_relationship(1).await?;
/// tracing::info!("Delete relationship result: {}", response.message);
/// # Ok(())
/// # }
/// ```
pub async fn delete_relationship(&self, rel_id: u64) -> Result<DeleteRelResponse> {
let mut params = HashMap::new();
params.insert("rel_id".to_string(), Value::Int(rel_id as i64));
let query = "MATCH ()-[r]->() WHERE id(r) = $rel_id DELETE r RETURN count(r) as deleted";
let _result = self.execute_cypher(query, Some(params)).await?;
Ok(DeleteRelResponse {
message: "Relationship deleted successfully".to_string(),
error: None,
})
}
}