Skip to main content

cognee_graph/
types.rs

1//! Type definitions for graph database operations.
2//!
3//! Type aliases for graph data structures:
4//! - NodeData: arbitrary key-value properties
5//! - EdgeData: (source_id, target_id, relationship_name, properties)
6//! - GraphNode: (node_id, properties)
7
8use serde::{Deserialize, Serialize};
9use std::borrow::Cow;
10use std::collections::HashMap;
11
12/// Node data: arbitrary key-value properties
13/// Uses Cow<'static, str> for keys to avoid allocating static strings
14pub type NodeData = HashMap<Cow<'static, str>, serde_json::Value>;
15
16/// Graph node: (node_id, properties)
17pub type GraphNode = (String, NodeData);
18
19/// Edge data: (source_id, target_id, relationship_name, properties)
20pub type EdgeData = (
21    String,
22    String,
23    String,
24    HashMap<Cow<'static, str>, serde_json::Value>,
25);
26
27/// Structured graph edge for easier construction
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct GraphEdge {
30    /// Source node ID
31    pub source_id: String,
32    /// Target node ID
33    pub target_id: String,
34    /// Relationship name (edge label)
35    pub relationship_name: String,
36    /// Edge properties
37    pub properties: HashMap<Cow<'static, str>, serde_json::Value>,
38}
39
40impl GraphEdge {
41    /// Create a new graph edge
42    pub fn new(source_id: String, target_id: String, relationship_name: String) -> Self {
43        Self {
44            source_id,
45            target_id,
46            relationship_name,
47            properties: HashMap::new(),
48        }
49    }
50
51    /// Create a new graph edge with properties
52    pub fn with_properties(
53        source_id: String,
54        target_id: String,
55        relationship_name: String,
56        properties: HashMap<Cow<'static, str>, serde_json::Value>,
57    ) -> Self {
58        Self {
59            source_id,
60            target_id,
61            relationship_name,
62            properties,
63        }
64    }
65
66    /// Convert to EdgeData tuple
67    pub fn to_edge_data(self) -> EdgeData {
68        (
69            self.source_id,
70            self.target_id,
71            self.relationship_name,
72            self.properties,
73        )
74    }
75
76    /// Create from EdgeData tuple
77    pub fn from_edge_data(edge: EdgeData) -> Self {
78        Self {
79            source_id: edge.0,
80            target_id: edge.1,
81            relationship_name: edge.2,
82            properties: edge.3,
83        }
84    }
85}
86
87impl From<GraphEdge> for EdgeData {
88    fn from(edge: GraphEdge) -> Self {
89        edge.to_edge_data()
90    }
91}
92
93impl From<EdgeData> for GraphEdge {
94    fn from(edge: EdgeData) -> Self {
95        GraphEdge::from_edge_data(edge)
96    }
97}