🕸️ Graph Database Simulator

WIA-DATA-015: Interactive Graph Database Operations

📋 Overview
🎮 Demo
🔌 API
💡 Examples
📚 Resources

Graph Database Overview

What is a Graph Database?

A graph database is a specialized database that uses graph structures with nodes, edges, and properties to represent and store data. Unlike traditional relational databases, graph databases excel at managing highly connected data and complex relationships.

Core Concepts

  • Nodes: Entities or objects (e.g., Person, Product)
  • Edges: Relationships between nodes (e.g., KNOWS, PURCHASED)
  • Properties: Key-value pairs stored on nodes and edges
  • Labels: Categories or types for nodes
  • Traversal: Navigation through connected nodes

Use Cases

  • Social Network Analysis
  • Recommendation Engines
  • Fraud Detection
  • Knowledge Graphs
  • Network & IT Operations
  • Master Data Management
  • Identity & Access Management

Simple Graph Example

Alice → KNOWS → Bob → LIKES → Coffee
Carol → FRIEND_OF → Alice

Popular Graph Databases

Database Query Language Type
Neo4j Cypher Property Graph
Amazon Neptune Gremlin, SPARQL Property Graph / RDF
ArangoDB AQL Multi-Model
JanusGraph Gremlin Property Graph

Interactive Demo

Query results will appear here...

Sample Queries to Try

// Find all friends of Alice
MATCH (p:Person {name: 'Alice'})-[:KNOWS]->(friend)
RETURN friend.name

// Find friends of friends
MATCH (p:Person {name: 'Alice'})-[:KNOWS*2]->(fof)
RETURN DISTINCT fof.name

// Find shortest path
MATCH path = shortestPath(
  (alice:Person {name: 'Alice'})-[:KNOWS*]-(bob:Person {name: 'Bob'})
)
RETURN path

// Create a new node
CREATE (n:Person {name: 'Dave', age: 30})
RETURN n

Graph Database API

RESTful API Endpoints

Base URL: https://api.wia-data-015.org/v1

# Execute Cypher Query
POST /query
Content-Type: application/json

{
  "query": "MATCH (n:Person) RETURN n LIMIT 10",
  "parameters": {}
}

# Create Node
POST /nodes
{
  "labels": ["Person"],
  "properties": {
    "name": "Alice",
    "age": 30
  }
}

# Create Relationship
POST /relationships
{
  "from": "node-id-123",
  "to": "node-id-456",
  "type": "KNOWS",
  "properties": {
    "since": "2020"
  }
}

# Get Node by ID
GET /nodes/{nodeId}

# Update Node
PUT /nodes/{nodeId}
{
  "properties": {
    "age": 31
  }
}

# Delete Node
DELETE /nodes/{nodeId}

# Graph Algorithms
POST /algorithms/shortestPath
{
  "start": "node-id-123",
  "end": "node-id-456",
  "relationshipType": "KNOWS"
}

JavaScript SDK Example

import { GraphDB } from '@wia/graph-database';

// Initialize connection
const graph = new GraphDB({
  uri: 'bolt://localhost:7687',
  user: 'neo4j',
  password: 'password'
});

// Create nodes
await graph.createNode({
  labels: ['Person'],
  properties: { name: 'Alice', age: 30 }
});

// Execute query
const result = await graph.query(`
  MATCH (p:Person)-[:KNOWS]->(friend)
  WHERE p.name = $name
  RETURN friend.name as friendName
`, { name: 'Alice' });

console.log(result);

// Close connection
await graph.close();

Python SDK Example

from wia_graph_db import GraphDB

# Connect to database
graph = GraphDB(
    uri="bolt://localhost:7687",
    user="neo4j",
    password="password"
)

# Create node
graph.create_node(
    labels=["Person"],
    properties={"name": "Alice", "age": 30}
)

# Execute query
result = graph.query("""
    MATCH (p:Person)-[:KNOWS]->(friend)
    WHERE p.name = $name
    RETURN friend.name as friendName
""", parameters={"name": "Alice"})

for record in result:
    print(record["friendName"])

# Close connection
graph.close()

Real-World Examples

Example 1: Social Network

// Create users
CREATE (alice:Person {name: 'Alice', age: 30, city: 'NYC'})
CREATE (bob:Person {name: 'Bob', age: 28, city: 'LA'})
CREATE (carol:Person {name: 'Carol', age: 32, city: 'NYC'})
CREATE (dave:Person {name: 'Dave', age: 35, city: 'SF'})

// Create friendships
CREATE (alice)-[:KNOWS {since: 2015}]->(bob)
CREATE (alice)-[:KNOWS {since: 2018}]->(carol)
CREATE (bob)-[:KNOWS {since: 2020}]->(dave)
CREATE (carol)-[:KNOWS {since: 2019}]->(dave)

// Find mutual friends
MATCH (alice:Person {name: 'Alice'})-[:KNOWS]-(mutual)-[:KNOWS]-(bob:Person {name: 'Bob'})
RETURN mutual.name

// Find people in same city
MATCH (p1:Person)-[:KNOWS]-(p2:Person)
WHERE p1.city = p2.city
RETURN p1.name, p2.name, p1.city

Example 2: Recommendation Engine

// Create products and purchases
CREATE (alice:User {name: 'Alice'})
CREATE (bob:User {name: 'Bob'})
CREATE (laptop:Product {name: 'Laptop', category: 'Electronics'})
CREATE (mouse:Product {name: 'Mouse', category: 'Electronics'})
CREATE (book:Product {name: 'Book', category: 'Books'})

CREATE (alice)-[:PURCHASED]->(laptop)
CREATE (alice)-[:PURCHASED]->(mouse)
CREATE (bob)-[:PURCHASED]->(laptop)

// Recommend products
MATCH (user:User {name: 'Bob'})-[:PURCHASED]->(:Product)<-[:PURCHASED]-(other:User)
MATCH (other)-[:PURCHASED]->(recommendation:Product)
WHERE NOT (user)-[:PURCHASED]->(recommendation)
RETURN recommendation.name, COUNT(*) as score
ORDER BY score DESC
LIMIT 5

Example 3: Fraud Detection

// Create accounts and transactions
CREATE (a1:Account {id: 'ACC001', owner: 'Alice'})
CREATE (a2:Account {id: 'ACC002', owner: 'Bob'})
CREATE (a3:Account {id: 'ACC003', owner: 'Carol'})

CREATE (a1)-[:TRANSFERRED {amount: 1000, date: '2024-01-15'}]->(a2)
CREATE (a2)-[:TRANSFERRED {amount: 950, date: '2024-01-16'}]->(a3)
CREATE (a3)-[:TRANSFERRED {amount: 900, date: '2024-01-17'}]->(a1)

// Detect circular transfers (potential fraud)
MATCH path = (a:Account)-[:TRANSFERRED*3..5]->(a)
RETURN path, length(path) as hops

// Find rapid successive transfers
MATCH (a1:Account)-[t1:TRANSFERRED]->(a2:Account)-[t2:TRANSFERRED]->(a3:Account)
WHERE duration.between(datetime(t1.date), datetime(t2.date)).days < 2
RETURN a1.owner, a2.owner, a3.owner, t1.amount, t2.amount

Example 4: Knowledge Graph

// Create knowledge entities
CREATE (einstein:Person {name: 'Albert Einstein', born: 1879})
CREATE (relativity:Theory {name: 'Theory of Relativity', year: 1915})
CREATE (physics:Field {name: 'Physics'})
CREATE (nobel:Award {name: 'Nobel Prize', year: 1921})

CREATE (einstein)-[:DEVELOPED]->(relativity)
CREATE (einstein)-[:WORKS_IN]->(physics)
CREATE (einstein)-[:RECEIVED]->(nobel)
CREATE (relativity)-[:PART_OF]->(physics)

// Query knowledge graph
MATCH (p:Person)-[:DEVELOPED]->(t:Theory)-[:PART_OF]->(f:Field)
WHERE f.name = 'Physics'
RETURN p.name, t.name, t.year
ORDER BY t.year

Resources & Documentation

Graph Database Platforms

Platform Description License
Neo4j Leading property graph database with Cypher query language GPL/Commercial
Amazon Neptune Fully managed graph database service Commercial
ArangoDB Multi-model database with graph capabilities Apache 2.0
JanusGraph Scalable graph database optimized for large graphs Apache 2.0
TigerGraph Native parallel graph database for analytics Commercial

Query Languages

Cypher (Neo4j)

MATCH (n:Person)-[:KNOWS]->(m:Person)
WHERE n.name = 'Alice'
RETURN m.name

Gremlin (Apache TinkerPop)

g.V().hasLabel('person')
  .has('name', 'Alice')
  .out('knows')
  .values('name')

Graph Algorithms

  • Pathfinding: Shortest Path, All Shortest Paths, A* Algorithm
  • Centrality: PageRank, Betweenness, Closeness, Degree
  • Community Detection: Louvain, Label Propagation, Weakly Connected Components
  • Similarity: Node Similarity, Jaccard Index, Cosine Similarity
  • Link Prediction: Adamic Adar, Common Neighbors, Preferential Attachment

Best Practices

  • Use labels and indexes for efficient queries
  • Limit traversal depth to prevent performance issues
  • Use parameters in queries to prevent injection attacks
  • Design schema based on query patterns
  • Use EXPLAIN and PROFILE for query optimization
  • Implement proper access control and authentication
  • Regular backups and monitoring
  • Consider data modeling before implementation