Skip to main content

nexus_sdk/
batch.rs

1//! Batch operations for efficient bulk data operations
2
3use crate::client::NexusClient;
4use crate::error::{NexusError, Result};
5use crate::models::Value;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9/// Batch create nodes request
10#[derive(Debug, Clone, Serialize)]
11pub struct BatchCreateNodesRequest {
12    /// List of nodes to create
13    pub nodes: Vec<BatchNode>,
14}
15
16/// Batch node definition
17#[derive(Debug, Clone, Serialize)]
18pub struct BatchNode {
19    /// Node labels
20    pub labels: Vec<String>,
21    /// Node properties
22    #[serde(default)]
23    pub properties: HashMap<String, Value>,
24}
25
26/// Batch create nodes response
27#[derive(Debug, Clone, Deserialize)]
28pub struct BatchCreateNodesResponse {
29    /// List of created node IDs
30    pub node_ids: Vec<u64>,
31    /// Success message
32    pub message: String,
33    /// Error message if any
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub error: Option<String>,
36}
37
38/// Batch create relationships request
39#[derive(Debug, Clone, Serialize)]
40pub struct BatchCreateRelationshipsRequest {
41    /// List of relationships to create
42    pub relationships: Vec<BatchRelationship>,
43}
44
45/// Batch relationship definition
46#[derive(Debug, Clone, Serialize)]
47pub struct BatchRelationship {
48    /// Source node ID
49    pub source_id: u64,
50    /// Target node ID
51    pub target_id: u64,
52    /// Relationship type
53    pub rel_type: String,
54    /// Relationship properties
55    #[serde(default)]
56    pub properties: HashMap<String, Value>,
57}
58
59/// Batch create relationships response
60#[derive(Debug, Clone, Deserialize)]
61pub struct BatchCreateRelationshipsResponse {
62    /// List of created relationship IDs
63    pub rel_ids: Vec<u64>,
64    /// Success message
65    pub message: String,
66    /// Error message if any
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub error: Option<String>,
69}
70
71impl NexusClient {
72    /// Batch create multiple nodes
73    ///
74    /// # Arguments
75    ///
76    /// * `nodes` - Vector of batch node definitions
77    ///
78    /// # Example
79    ///
80    /// ```no_run
81    /// # use nexus_sdk::{NexusClient, Value};
82    /// # use std::collections::HashMap;
83    /// # #[tokio::main]
84    /// # async fn main() -> Result<(), nexus_sdk::NexusError> {
85    /// # let client = NexusClient::new("http://localhost:15474")?;
86    /// let mut nodes = Vec::new();
87    /// for i in 0..10 {
88    ///     let mut properties = HashMap::new();
89    ///     properties.insert("name".to_string(), Value::String(format!("Node{}", i)));
90    ///     nodes.push(nexus_sdk::BatchNode {
91    ///         labels: vec!["Person".to_string()],
92    ///         properties,
93    ///     });
94    /// }
95    /// let response = client.batch_create_nodes(nodes).await?;
96    /// tracing::info!("Created {} nodes", response.node_ids.len());
97    /// # Ok(())
98    /// # }
99    /// ```
100    pub async fn batch_create_nodes(
101        &self,
102        nodes: Vec<BatchNode>,
103    ) -> Result<BatchCreateNodesResponse> {
104        // For now, create nodes sequentially
105        // TODO: Implement proper batch endpoint if available
106        let mut node_ids = Vec::new();
107        let mut errors = Vec::new();
108
109        for node in nodes {
110            match self.create_node(node.labels, node.properties).await {
111                Ok(response) => node_ids.push(response.node_id),
112                Err(e) => errors.push(format!("Failed to create node: {}", e)),
113            }
114        }
115
116        if !errors.is_empty() {
117            return Err(NexusError::Validation(format!(
118                "Some nodes failed to create: {}",
119                errors.join(", ")
120            )));
121        }
122
123        let node_count = node_ids.len();
124        Ok(BatchCreateNodesResponse {
125            node_ids,
126            message: format!("Successfully created {} nodes", node_count),
127            error: None,
128        })
129    }
130
131    /// Batch create multiple relationships
132    ///
133    /// # Arguments
134    ///
135    /// * `relationships` - Vector of batch relationship definitions
136    ///
137    /// # Example
138    ///
139    /// ```no_run
140    /// # use nexus_sdk::{NexusClient, Value};
141    /// # use std::collections::HashMap;
142    /// # #[tokio::main]
143    /// # async fn main() -> Result<(), nexus_sdk::NexusError> {
144    /// # let client = NexusClient::new("http://localhost:15474")?;
145    /// let mut relationships = Vec::new();
146    /// for i in 0..5 {
147    ///     relationships.push(nexus_sdk::BatchRelationship {
148    ///         source_id: i,
149    ///         target_id: i + 1,
150    ///         rel_type: "KNOWS".to_string(),
151    ///         properties: HashMap::new(),
152    ///     });
153    /// }
154    /// let response = client.batch_create_relationships(relationships).await?;
155    /// tracing::info!("Created {} relationships", response.rel_ids.len());
156    /// # Ok(())
157    /// # }
158    /// ```
159    pub async fn batch_create_relationships(
160        &self,
161        relationships: Vec<BatchRelationship>,
162    ) -> Result<BatchCreateRelationshipsResponse> {
163        // For now, create relationships sequentially
164        // TODO: Implement proper batch endpoint if available
165        let mut rel_ids = Vec::new();
166        let mut errors = Vec::new();
167
168        for rel in relationships {
169            match self
170                .create_relationship(rel.source_id, rel.target_id, rel.rel_type, rel.properties)
171                .await
172            {
173                Ok(response) => rel_ids.push(response.rel_id),
174                Err(e) => errors.push(format!("Failed to create relationship: {}", e)),
175            }
176        }
177
178        if !errors.is_empty() {
179            return Err(NexusError::Validation(format!(
180                "Some relationships failed to create: {}",
181                errors.join(", ")
182            )));
183        }
184
185        let rel_count = rel_ids.len();
186        Ok(BatchCreateRelationshipsResponse {
187            rel_ids,
188            message: format!("Successfully created {} relationships", rel_count),
189            error: None,
190        })
191    }
192}