Graph Database: Use Cases
Graph Database: Use Cases
Part of: Graph Database User Guide
Use Case 1: Social Network Analysis
Scenario: Build a social network with friend recommendations and influencer detection.
Step 1: Model the Graph
// Nodes: Users// Edges: FRIEND_OF, FOLLOWS, LIKES
// Create userslet users = vec![ ("alice", 28, "San Francisco"), ("bob", 32, "New York"), ("charlie", 25, "San Francisco"), ("diana", 30, "Seattle"), ("eve", 27, "San Francisco"),];
let mut user_ids = HashMap::new();
for (name, age, city) in users { let node = Node { id: 0, label: "User".to_string(), properties: HashMap::from([ ("username".to_string(), json!(name)), ("age".to_string(), json!(age)), ("city".to_string(), json!(city)), ]), }; let id = storage.add_vertex(node).await?; user_ids.insert(name, id);}
// Create friendshipslet friendships = vec![ ("alice", "bob"), ("alice", "charlie"), ("bob", "charlie"), ("charlie", "diana"), ("diana", "eve"),];
for (from, to) in friendships { let edge = Edge { id: 0, source: *user_ids.get(from).unwrap(), target: *user_ids.get(to).unwrap(), label: "FRIEND_OF".to_string(), weight: 1.0, properties: HashMap::new(), }; storage.add_edge(edge).await?;}Step 2: Friend Recommendations
// Find friends of friends (not already friends)async fn recommend_friends( storage: &GraphStorage, user_id: NodeId,) -> Result<Vec<NodeId>> { // Get direct friends let direct_friends: HashSet<NodeId> = storage .get_outgoing_edges(user_id).await? .into_iter() .map(|e| e.target) .collect();
// Get friends of friends let mut fof = HashSet::new(); for friend_id in &direct_friends { let friends_of_friend = storage.get_outgoing_edges(*friend_id).await?; for edge in friends_of_friend { // Exclude self and direct friends if edge.target != user_id && !direct_friends.contains(&edge.target) { fof.insert(edge.target); } } }
Ok(fof.into_iter().collect())}
// Use itlet recommendations = recommend_friends(&storage, user_ids["alice"]).await?;println!("Friend recommendations for Alice:");for user_id in recommendations { if let Some(user) = storage.get_vertex(user_id).await? { println!(" - {}", user.properties.get("username").unwrap()); }}Step 3: Find Influencers
let all_user_ids: Vec<NodeId> = user_ids.values().copied().collect();
// Run PageRank to find influencerslet ranks = pagerank(&storage, &all_user_ids, 0.85, 50, 0.0001).await?;
let mut sorted: Vec<_> = ranks.iter().collect();sorted.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap());
println!("Top influencers:");for (user_id, rank) in sorted.iter().take(5) { if let Some(user) = storage.get_vertex(**user_id).await? { println!(" {} - Influence score: {:.4}", user.properties.get("username").unwrap(), rank); }}Step 4: Detect Communities
let result = louvain(&storage, &all_user_ids, 1.0).await?;
println!("Social communities detected: {}", result.num_communities);
// Group users by communitylet mut communities: HashMap<usize, Vec<String>> = HashMap::new();for (user_id, community_id) in result.communities { if let Some(user) = storage.get_vertex(user_id).await? { let username = user.properties.get("username").unwrap().as_str().unwrap().to_string(); communities.entry(community_id).or_insert_with(Vec::new).push(username); }}
for (community_id, members) in communities { println!("Community {}: {:?}", community_id, members);}Performance: Process 10M user graph in <5 seconds
Use Case 2: Fraud Detection
Scenario: Detect fraudulent accounts and transaction rings in a financial network.
Step 1: Model Financial Network
// Nodes: Accounts, Transactions// Edges: TRANSFERRED_TO, OWNS
// Create accountslet accounts = vec![ ("acc_001", "Alice", true), // legitimate ("acc_002", "Bob", true), ("acc_003", "Fraudster1", false), ("acc_004", "Fraudster2", false), ("acc_005", "Fraudster3", false),];
let mut account_ids = HashMap::new();
for (acc_num, owner, is_legitimate) in accounts { let node = Node { id: 0, label: "Account".to_string(), properties: HashMap::from([ ("account_number".to_string(), json!(acc_num)), ("owner".to_string(), json!(owner)), ("is_legitimate".to_string(), json!(is_legitimate)), ]), }; let id = storage.add_vertex(node).await?; account_ids.insert(acc_num, id);}
// Create transactions (including circular pattern)let transactions = vec![ ("acc_001", "acc_002", 1000.0), ("acc_003", "acc_004", 5000.0), ("acc_004", "acc_005", 5000.0), ("acc_005", "acc_003", 4500.0), // Circular!];
for (from, to, amount) in transactions { let edge = Edge { id: 0, source: *account_ids.get(from).unwrap(), target: *account_ids.get(to).unwrap(), label: "TRANSFERRED_TO".to_string(), weight: amount, properties: HashMap::from([ ("amount".to_string(), json!(amount)), ("timestamp".to_string(), json!("2025-11-01T10:00:00Z")), ]), }; storage.add_edge(edge).await?;}Step 2: Detect Circular Transactions (Money Laundering)
use heliosdb_graph::traversal::{dfs, DfsOptions};
// Run DFS with cycle detection on each accountlet all_account_ids: Vec<NodeId> = account_ids.values().copied().collect();
let mut suspicious_accounts = Vec::new();
for account_id in &all_account_ids { let options = DfsOptions { max_depth: 10, detect_cycles: true, enable_early_termination: false, target: None, };
let result = dfs(&storage, *account_id, options).await?;
if !result.cycles.is_empty() { suspicious_accounts.push(*account_id); println!("Circular transactions detected for account: {:?}", account_id); for cycle in result.cycles { println!(" Cycle: {:?}", cycle); } }}Step 3: Detect Fraud Rings (Connected Components)
use heliosdb_graph::algorithms::weakly_connected_components;
let components = weakly_connected_components(&storage, &all_account_ids).await?;
println!("Connected components (potential fraud rings):");for (component_id, members) in components { if members.len() > 2 { println!("Fraud ring {} with {} members:", component_id, members.len()); for account_id in members { if let Some(account) = storage.get_vertex(account_id).await? { println!(" - {}", account.properties.get("account_number").unwrap()); } } }}Step 4: Find Money Mules (High Betweenness)
let betweenness = betweenness_centrality(&storage, &all_account_ids).await?;
let mut sorted: Vec<_> = betweenness.iter().collect();sorted.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap());
println!("Potential money mule accounts (high betweenness):");for (account_id, score) in sorted.iter().take(5) { if *score > 0.5 { // Threshold if let Some(account) = storage.get_vertex(**account_id).await? { println!(" {} - Betweenness: {:.4}", account.properties.get("account_number").unwrap(), score); } }}Key Indicators:
- Circular transactions (cycles)
- Connected suspicious accounts (components)
- Accounts that route many transactions (betweenness)
Use Case 3: Recommendation Engine
Scenario: Product recommendations based on collaborative filtering.
Step 1: Model User-Product Graph
// Create users and products// Edges: PURCHASED, VIEWED, RATED
// Productslet products = vec![ ("prod_001", "Laptop", 999.99), ("prod_002", "Mouse", 29.99), ("prod_003", "Keyboard", 79.99), ("prod_004", "Monitor", 299.99),];
let mut product_ids = HashMap::new();
for (prod_id, name, price) in products { let node = Node { id: 0, label: "Product".to_string(), properties: HashMap::from([ ("product_id".to_string(), json!(prod_id)), ("name".to_string(), json!(name)), ("price".to_string(), json!(price)), ]), }; let id = storage.add_vertex(node).await?; product_ids.insert(prod_id, id);}
// Purchaseslet purchases = vec![ ("alice", "prod_001"), ("alice", "prod_002"), ("bob", "prod_001"), ("bob", "prod_003"), ("charlie", "prod_002"), ("charlie", "prod_003"),];
for (user, product) in purchases { let edge = Edge { id: 0, source: *user_ids.get(user).unwrap(), target: *product_ids.get(product).unwrap(), label: "PURCHASED".to_string(), weight: 1.0, properties: HashMap::new(), }; storage.add_edge(edge).await?;}Step 2: Collaborative Filtering
async fn recommend_products( storage: &GraphStorage, user_id: NodeId, limit: usize,) -> Result<Vec<(NodeId, f64)>> { // Find products user already purchased let purchased: HashSet<NodeId> = storage .get_outgoing_edges(user_id).await? .into_iter() .filter(|e| e.label == "PURCHASED") .map(|e| e.target) .collect();
// Find similar users (who bought the same products) let mut similar_users = HashSet::new(); for product_id in &purchased { let buyers = storage.get_incoming_edges(*product_id).await?; for edge in buyers { if edge.source != user_id { similar_users.insert(edge.source); } } }
// Find products purchased by similar users let mut product_scores: HashMap<NodeId, f64> = HashMap::new(); for similar_user in similar_users { let their_purchases = storage.get_outgoing_edges(similar_user).await?; for edge in their_purchases { if edge.label == "PURCHASED" && !purchased.contains(&edge.target) { *product_scores.entry(edge.target).or_insert(0.0) += 1.0; } } }
// Sort by score let mut recommendations: Vec<_> = product_scores.into_iter().collect(); recommendations.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); recommendations.truncate(limit);
Ok(recommendations)}
// Generate recommendationslet recommendations = recommend_products(&storage, user_ids["alice"], 5).await?;
println!("Recommended products for Alice:");for (product_id, score) in recommendations { if let Some(product) = storage.get_vertex(product_id).await? { println!(" {} (score: {:.1})", product.properties.get("name").unwrap(), score); }}Performance: <10ms per recommendation query
Use Case 4: Knowledge Graph
Scenario: Entity relationship queries for a knowledge base.
Step 1: Build Knowledge Graph
// Entities: Person, Company, Technology// Relationships: WORKS_FOR, INVENTED, USES
let entities = vec![ ("Larry Page", "Person"), ("Sergey Brin", "Person"), ("Google", "Company"), ("PageRank", "Technology"),];
let mut entity_ids = HashMap::new();
for (name, entity_type) in entities { let node = Node { id: 0, label: entity_type.to_string(), properties: HashMap::from([ ("name".to_string(), json!(name)), ]), }; let id = storage.add_vertex(node).await?; entity_ids.insert(name, id);}
let relationships = vec![ ("Larry Page", "WORKS_FOR", "Google"), ("Sergey Brin", "WORKS_FOR", "Google"), ("Larry Page", "INVENTED", "PageRank"), ("Sergey Brin", "INVENTED", "PageRank"), ("Google", "USES", "PageRank"),];
for (from, rel_type, to) in relationships { let edge = Edge { id: 0, source: *entity_ids.get(from).unwrap(), target: *entity_ids.get(to).unwrap(), label: rel_type.to_string(), weight: 1.0, properties: HashMap::new(), }; storage.add_edge(edge).await?;}Step 2: Query Relationships
// Find all inventors of PageRanklet pagerank_id = entity_ids["PageRank"];let inventors = storage.get_incoming_edges(pagerank_id).await?;
println!("Inventors of PageRank:");for edge in inventors { if edge.label == "INVENTED" { if let Some(person) = storage.get_vertex(edge.source).await? { println!(" - {}", person.properties.get("name").unwrap()); } }}
// Find shortest path between two conceptslet path = dijkstra( &storage, entity_ids["Larry Page"], entity_ids["PageRank"]).await?;
if let Some(path) = path { println!("\nConnection between Larry Page and PageRank:"); for (i, node_id) in path.path.iter().enumerate() { if let Some(node) = storage.get_vertex(*node_id).await? { println!(" {}. {} ({})", i + 1, node.properties.get("name").unwrap(), node.label); } }}Use Case 5: Supply Chain Optimization
Scenario: Optimize delivery routes and detect bottlenecks.
Step 1: Model Supply Chain
// Nodes: Warehouses, Distribution Centers, Stores// Edges: SHIPS_TO (with distance/cost as weight)
let locations = vec![ ("Warehouse_A", "Warehouse", 37.7749, -122.4194), ("DC_1", "DistributionCenter", 37.3382, -121.8863), ("Store_1", "Store", 37.7858, -122.4064), ("Store_2", "Store", 37.8044, -122.2712),];
let mut location_ids = HashMap::new();
for (name, loc_type, lat, lon) in locations { let node = Node { id: 0, label: loc_type.to_string(), properties: HashMap::from([ ("name".to_string(), json!(name)), ("latitude".to_string(), json!(lat)), ("longitude".to_string(), json!(lon)), ]), }; let id = storage.add_vertex(node).await?; location_ids.insert(name, id);}
// Routes with distances (km)let routes = vec![ ("Warehouse_A", "DC_1", 50.0), ("DC_1", "Store_1", 10.0), ("DC_1", "Store_2", 25.0), ("Warehouse_A", "Store_1", 55.0), // Direct route];
for (from, to, distance) in routes { let edge = Edge { id: 0, source: *location_ids.get(from).unwrap(), target: *location_ids.get(to).unwrap(), label: "SHIPS_TO".to_string(), weight: distance, properties: HashMap::from([ ("distance_km".to_string(), json!(distance)), ]), }; storage.add_edge(edge).await?;}Step 2: Find Optimal Delivery Route
// Find cheapest route from warehouse to storelet optimal_route = dijkstra( &storage, location_ids["Warehouse_A"], location_ids["Store_1"]).await?;
if let Some(path) = optimal_route { println!("Optimal delivery route:"); println!(" Total distance: {:.1} km", path.cost);
for (i, location_id) in path.path.iter().enumerate() { if let Some(location) = storage.get_vertex(*location_id).await? { println!(" {}. {}", i + 1, location.properties.get("name").unwrap()); } }}Step 3: Detect Critical Nodes (Bottlenecks)
let all_locations: Vec<NodeId> = location_ids.values().copied().collect();
let betweenness = betweenness_centrality(&storage, &all_locations).await?;
println!("\nCritical supply chain nodes:");for (location_id, score) in betweenness { if score > 0.3 { if let Some(location) = storage.get_vertex(location_id).await? { println!(" {} - Criticality: {:.4}", location.properties.get("name").unwrap(), score); } }}Use Case 6: Network Analysis
Scenario: Analyze computer network topology.
// Nodes: Routers, Switches, Servers// Edges: CONNECTED_TO (with bandwidth as weight)
// Similar setup to supply chain...
// Find network diameter (longest shortest path)let all_nodes: Vec<NodeId> = /* ... */;let mut max_distance = 0.0;
for i in 0..all_nodes.len() { for j in (i+1)..all_nodes.len() { if let Some(path) = dijkstra(&storage, all_nodes[i], all_nodes[j]).await? { if path.cost > max_distance { max_distance = path.cost; } } }}
println!("Network diameter: {:.1}", max_distance);
// Find hub routerslet degree = degree_centrality(&storage, &all_nodes, DegreeMode::Total).await?;// ... analyze resultsNavigation
- Previous: Graph Algorithms
- Next: Performance Optimization
- Index: Graph Database User Guide
Version: 6.5 Last Updated: November 17, 2025