Skip to content

data.graphdb #

GraphDB

A lightweight, efficient graph database implementation in V that supports property graphs with nodes and edges. It provides both in-memory caching and persistent storage capabilities.

Features

  • Property Graph Model
  • Nodes with key-value properties
  • Typed edges with properties
  • Bidirectional edge traversal
  • Persistent Storage
  • Automatic data persistence
  • Efficient serialization
  • Memory-Efficient Caching
  • LRU caching for nodes and edges
  • Configurable cache sizes
  • Rich Query Capabilities
  • Property-based node queries
  • Edge-based node traversal
  • Relationship type filtering
  • CRUD Operations
  • Create, read, update, and delete nodes
  • Manage relationships between nodes
  • Update properties dynamically

Installation

GraphDB is part of the HeroLib library. Include it in your V project:

import freeflowuniverse.herolib.data.graphdb

Basic Usage

Here's a simple example demonstrating core functionality:

import freeflowuniverse.herolib.data.graphdb

fn main() {
    // Create a new graph database
    mut gdb := graphdb.new(path: '/tmp/mydb', reset: true)!

    // Create nodes
    user_id := gdb.create_node({
        'name': 'John',
        'age': '30',
        'city': 'London'
    })!

    company_id := gdb.create_node({
        'name': 'TechCorp',
        'industry': 'Technology'
    })!

    // Create relationship
    gdb.create_edge(user_id, company_id, 'WORKS_AT', {
        'role': 'Developer',
        'since': '2022'
    })!

    // Query nodes by property
    london_users := gdb.query_nodes_by_property('city', 'London')!

    // Find connected nodes
    workplaces := gdb.get_connected_nodes(user_id, 'WORKS_AT', 'out')!
}

API Reference

Creating a Database

// Create new database instance
struct NewArgs {
    path         string        // Storage path
    reset        bool          // Clear existing data
    cache_config CacheConfig   // Optional cache configuration
}
db := graphdb.new(NewArgs{...})!

Node Operations

// Create node
node_id := db.create_node(properties: map[string]string)!

// Get node
node := db.get_node(id: u32)!

// Update node
db.update_node(id: u32, properties: map[string]string)!

// Delete node (and connected edges)
db.delete_node(id: u32)!

// Query nodes by property
nodes := db.query_nodes_by_property(key: string, value: string)!

Edge Operations

// Create edge
edge_id := db.create_edge(from_id: u32, to_id: u32, edge_type: string, properties: map[string]string)!

// Get edge
edge := db.get_edge(id: u32)!

// Update edge
db.update_edge(id: u32, properties: map[string]string)!

// Delete edge
db.delete_edge(id: u32)!

// Get edges between nodes
edges := db.get_edges_between(from_id: u32, to_id: u32)!

Graph Traversal

// Get connected nodes
// direction can be 'in', 'out', or 'both'
nodes := db.get_connected_nodes(id: u32, edge_type: string, direction: string)!

Data Model

Node Structure

struct Node {
    id         u32                // Unique identifier
    properties map[string]string  // Key-value properties
    node_type  string            // Type of node
    edges_out  []EdgeRef         // Outgoing edge references
    edges_in   []EdgeRef         // Incoming edge references
}

Edge Structure

struct Edge {
    id         u32                // Unique identifier
    from_node  u32               // Source node ID
    to_node    u32               // Target node ID
    edge_type  string            // Type of relationship
    properties map[string]string  // Key-value properties
    weight     u16               // Edge weight
}

Performance Considerations

  • The database uses LRU caching for both nodes and edges to improve read performance
  • Persistent storage is handled efficiently through the underlying OurDB implementation
  • Edge references are stored in both source and target nodes for efficient traversal
  • Property queries perform full scans - consider indexing needs for large datasets

Example Use Cases

  • Social Networks: Modeling user relationships and interactions
  • Knowledge Graphs: Representing connected information and metadata
  • Organization Charts: Modeling company structure and relationships
  • Recommendation Systems: Building relationship-based recommendation engines

fn deserialize_edge #

fn deserialize_edge(data []u8) !Edge

Deserializes bytes to an Edge struct

fn deserialize_node #

fn deserialize_node(data []u8) !Node

Deserializes bytes to a Node struct

fn new #

fn new(args NewArgs) !&GraphDB

Creates a new graph database instance

fn serialize_edge #

fn serialize_edge(edge Edge) []u8

Serializes an Edge struct to bytes

fn serialize_node #

fn serialize_node(node Node) []u8

Serializes a Node struct to bytes

struct Edge #

@[heap]
struct Edge {
pub mut:
	id         u32               // Unique identifier
	from_node  u32               // Source node ID
	to_node    u32               // Target node ID
	edge_type  string            // Type of relationship
	properties map[string]string // Key-value properties
	weight     u16               // weight of the connection between the objects
}

Edge represents a connection between nodes with properties

struct EdgeRef #

@[heap]
struct EdgeRef {
pub mut:
	edge_id   u32    // Database ID of the edge
	edge_type string // Type of the edge relationship
}

EdgeRef is a lightweight reference to an edge

struct GraphDB #

struct GraphDB {
mut:
	db         &ourdb.OurDB // Database for persistent storage
	node_cache &Cache[Node] // Cache for nodes
	edge_cache &Cache[Edge] // Cache for edges
}

GraphDB represents the graph database

fn (GraphDB) create_edge #

fn (mut gdb GraphDB) create_edge(from_id u32, to_id u32, edge_type string, properties map[string]string) !u32

Creates an edge between two nodes

fn (GraphDB) create_node #

fn (mut gdb GraphDB) create_node(properties map[string]string) !u32

Creates a new node with the given properties

fn (GraphDB) debug_db #

fn (mut gdb GraphDB) debug_db() !

Prints the current state of the database

fn (GraphDB) debug_edge #

fn (mut gdb GraphDB) debug_edge(id u32) !string

Gets detailed information about an edge

fn (GraphDB) debug_node #

fn (mut gdb GraphDB) debug_node(id u32) !string

Gets detailed information about a node

fn (GraphDB) delete_edge #

fn (mut gdb GraphDB) delete_edge(id u32) !

Deletes an edge and updates connected nodes

fn (GraphDB) delete_node #

fn (mut gdb GraphDB) delete_node(id u32) !

Deletes a node and all its edges

fn (GraphDB) get_connected_nodes #

fn (mut gdb GraphDB) get_connected_nodes(id u32, edge_type string, direction string) ![]Node

Gets all nodes connected to a given node by edge type

fn (GraphDB) get_edge #

fn (mut gdb GraphDB) get_edge(id u32) !Edge

Gets an edge by its ID

fn (GraphDB) get_edges_between #

fn (mut gdb GraphDB) get_edges_between(from_id u32, to_id u32) ![]Edge

Gets all edges between two nodes

fn (GraphDB) get_node #

fn (mut gdb GraphDB) get_node(id u32) !Node

Gets a node by its ID

fn (GraphDB) print_graph #

fn (mut gdb GraphDB) print_graph() !

Prints a visual representation of the entire graph

fn (GraphDB) print_graph_from #

fn (mut gdb GraphDB) print_graph_from(start_id u32, visited map[u32]bool) !

Prints a visual representation of the graph starting from a given node

fn (GraphDB) query_nodes_by_property #

fn (mut gdb GraphDB) query_nodes_by_property(key string, value string) ![]Node

Queries nodes by property value

fn (GraphDB) search #

fn (mut gdb GraphDB) search(start_id u32, config SearchConfig) ![]SearchResult

search performs a breadth-first traversal from a start node Returns nodes of specified types within max_distance

fn (GraphDB) update_edge #

fn (mut gdb GraphDB) update_edge(id u32, properties map[string]string) !

Updates an edge's properties

fn (GraphDB) update_node #

fn (mut gdb GraphDB) update_node(id u32, properties map[string]string) !

Updates a node's properties

struct NewArgs #

struct NewArgs {
pub mut:
	path         string
	reset        bool
	cache_config CacheConfig = CacheConfig{} // Default cache configuration
}

struct Node #

@[heap]
struct Node {
pub mut:
	id         u32               // Unique identifier
	properties map[string]string // Key-value properties
	node_type  string            // Type of node can e.g. refer to a object implementation e.g. a User, ...
	edges_out  []EdgeRef         // Outgoing edge references
	edges_in   []EdgeRef         // Incoming edge references
}

Node represents a vertex in the graph with properties and edge references

struct SearchConfig #

struct SearchConfig {
pub mut:
	types        []string // List of node types to search for
	max_distance f32      // Maximum distance to traverse using edge weights
}

SearchConfig represents the configuration for graph traversal search

struct SearchResult #

struct SearchResult {
pub:
	node     &Node
	distance f32
}

SearchResult represents a node found during search with its distance from start