Introduction
Neo4j powers production applications across diverse industries, from social networks to financial services, from healthcare to telecommunications. Understanding real-world use cases helps you envision how graph databases can solve your specific challenges. This article explores detailed production use cases with schema designs, query patterns, and implementation strategies that have proven successful.
Social Networks and Communities
Social networks are inherently graph-shaped, making Neo4j the ideal database for social applications.
Friend Discovery and Recommendations
// Schema
CREATE (p:Person:User {
userId: 'user123',
name: 'Alice',
age: 30,
interests: ['technology', 'music']
})
// Friends of friends (potential friends)
MATCH (alice:User {userId: 'user123'})-[:FRIEND]->(friend)-[:FRIEND]-(fof)
WHERE NOT (alice)-[:FRIEND]-(fof)
AND fof <> alice
RETURN fof.name AS suggested, count(*) AS mutualFriends
ORDER BY mutualFriends DESC
LIMIT 10
// Find users with similar interests
MATCH (alice:User {userId: 'user123'}), (other:User)
WHERE any(interest IN other.interests WHERE interest IN alice.interests)
AND NOT (alice)-[:FRIEND]-(other)
RETURN other.name AS suggestedUser,
size(apoc.coll.intersection(alice.interests, other.interests)) AS commonInterests
ORDER BY commonInterests DESC
LIMIT 5
Analyzing Social Influence
// Calculate influence scores using PageRank
CALL gds.pageRank.write('socialGraph', {
writeProperty: 'influenceScore'
})
// Find key influencers
MATCH (u:User)
RETURN u.name, u.influenceScore AS score
ORDER BY score DESC
LIMIT 20
// Find communities
CALL gds.labelPropagation.write('socialGraph', {
writeProperty: 'community'
})
Content Feed Generation
// Personalized feed - content from friends and similar users
MATCH (user:User {userId: 'user123'})
MATCH (user)-[:FRIEND]-(friend)-[:POSTED]->(content)
WHERE content.timestamp > timestamp() - 604800000 // Last week
WITH user, content, friend
OPTIONAL MATCH (content)<-[:LIKED]-(liker)
WITH content, friend, count(liker) AS likes
WHERE likes > 5 // Filter by engagement
RETURN content.body AS post, friend.name AS author, likes
ORDER BY content.timestamp DESC, likes DESC
LIMIT 50
Fraud Detection
Financial fraud detection relies heavily on connection analysis—Neo4j excels at detecting suspicious patterns.
Transaction Network Analysis
// Schema for financial network
CREATE (t:Transaction {
transactionId: 'txn001',
amount: 5000,
timestamp: timestamp(),
merchant: 'StoreA'
})
CREATE (account1:Account {accountId: 'acc001', type: 'checking'})
CREATE (account2:Account {accountId: 'acc002', type: 'savings'})
CREATE (account1)-[:SENT {amount: 5000, timestamp: timestamp()}]->(account2)
Detect Circular Transactions
// Find circular money flows (potential money laundering)
MATCH path = (a:Account)-[:SENT*3..5]->(a)
WHERE a.accountId = 'acc001'
WITH path, relationships(path) AS rels
WHERE ALL(r IN rels WHERE r.amount > 1000)
RETURN path,
REDUCE(total = 0, r IN rels | total + r.amount) AS totalFlow
ORDER BY totalFlow DESC
LIMIT 10
Velocity and Pattern Detection
// High velocity transactions - many small transactions
MATCH (a:Account)-[r:SENT]->()
WHERE r.timestamp > timestamp() - 3600000 // Last hour
WITH a, count(r) AS txnCount, sum(r.amount) AS totalAmount
WHERE txnCount > 10 OR totalAmount > 50000
RETURN a.accountId, txnCount, totalAmount
ORDER BY totalAmount DESC
// Detect structured transactions (breaking into smaller amounts)
MATCH (a:Account)-[r:SENT]->(b:Account)
WHERE r.timestamp > timestamp() - 86400000 // Last day
WITH a, b, collect(r.amount) AS amounts, sum(r.amount) AS total
WHERE size(amounts) >= 3
AND total > 9000
AND apoc.coll.max(amounts) < 3000 // Each under threshold
RETURN a.accountId, amounts, total
Identity Network Analysis
// Find shared identifiers (phone, email, address) between accounts
MATCH (a1:Account)-[:HAS_EMAIL|HAS_PHONE|HAS_ADDRESS]-(shared)-[:HAS_EMAIL|HAS_PHONE|HAS_ADDRESS]-(a2:Account)
WHERE a1 <> a2
WITH a1, a2, count(shared) AS sharedIdentifiers
WHERE sharedIdentifiers >= 2
RETURN a1.accountId AS account1, a2.accountId AS account2, sharedIdentifiers
ORDER BY sharedIdentifiers DESC
LIMIT 20
Recommendation Engines
Graph-based recommendations leverage complex relationship patterns.
Product Recommendations
// Collaborative filtering - users who bought this also bought
MATCH (buyer:Account)-[:BOUGHT]->(product)<-[:BOUGHT]-(other:Account)
WHERE buyer <> other
WITH buyer, product, count(other) AS similarBuyers
WHERE similarBuyers > 10
MATCH (other)-[:BOUGHT]->(recommendation)
WHERE NOT (buyer)-[:BOUGHT]->(recommendation)
RETURN buyer.name AS forUser,
recommendation.name AS recommendedProduct,
similarBuyers
ORDER BY similarBuyers DESC
LIMIT 10
// Content-based recommendations
MATCH (user:User {userId: 'user123'})-[:VIEWED]->(p:Product)
WITH user, collect(p.category) AS viewedCategories
MATCH (rec:Product)
WHERE rec.category IN viewedCategories
AND NOT (user)-[:BOUGHT]->(rec)
RETURN rec.name, rec.category
LIMIT 10
Context-Aware Recommendations
// Time-aware recommendations
MATCH (user:User {userId: 'user123'})-[:BOUGHT]->(p:Product)
WITH user, p, p.category AS cat,
max(p.purchaseDate) AS lastPurchase
MATCH (rec:Product {category: cat})
WHERE rec.purchaseDate > lastPurchase - 2592000000 // Purchased in last month
AND NOT (user)-[:BOUGHT]->(rec)
RETURN rec.name, rec.purchaseDate
ORDER BY rec.purchaseDate DESC
LIMIT 10
Network and IT Operations
Infrastructure management involves complex dependencies—graphs model these naturally.
Dependency Mapping
// Create application dependency graph
CREATE (app:Service {name: 'api-gateway'})
CREATE (app2:Service {name: 'user-service'})
CREATE (app3:Service {name: 'payment-service'})
CREATE (db:Database {name: 'users-db'})
CREATE (db2:Database {name: 'payments-db'})
CREATE (app)-[:DEPENDS_ON]->(app2)
CREATE (app)-[:DEPENDS_ON]->(app3)
CREATE (app2)-[:DEPENDS_ON]->(db)
CREATE (app3)-[:DEPENDS_ON]->(db2)
// Impact analysis - what fails if this service goes down?
MATCH (failing:Service {name: 'user-service'})
MATCH path = (failing)<-[:DEPENDS_ON*1..]-(dependent)
RETURN DISTINCT dependent.name AS impactedService,
length(path) AS hopsAway
ORDER BY hopsAway
Root Cause Analysis
// Find root cause of alert
MATCH (alert:Alert {id: 'alert123'})
MATCH path = (alert)<-[:CAUSED]-()-[:CAUSED*0..5]-(:Issue)
WITH path, nodes(path) AS nodes
WHERE NOT ()-[:CAUSED]->(nodes[0]) // First node has no incoming causes
RETURN nodes[0] AS rootCause
Change Impact Analysis
// What services might be affected by database changes?
MATCH (db:Database {name: 'users-db'})
MATCH (db)<-[:DEPENDS_ON*1..]-(service)
RETURN service.name AS affectedService,
size((service)<-[:DEPENDS_ON]-()) AS dependents
ORDER BY dependents DESC
Healthcare and Life Sciences
Healthcare applications benefit from complex relationship modeling.
Patient Journey Analysis
// Patient medical history graph
CREATE (patient:Patient {patientId: 'p001', name: 'John'})
CREATE (encounter:Encounter {date: date('2025-01-15'), type: 'outpatient'})
CREATE (condition:Condition {code: 'E11.2', name: 'Type 2 Diabetes'})
CREATE (medication:Medication {name: 'Metformin', dosage: '500mg'})
CREATE (patient)-[:HAS_ENCOUNTER]->(encounter)
CREATE (encounter)-[:DIAGNOSED]->(condition)
CREATE (encounter)-[:PRESCRIBED]->(medication)
// Find patient care patterns
MATCH (patient:Patient)-[:HAS_ENCOUNTER]->()-[:DIAGNOSED]->(c:Condition {name: 'Type 2 Diabetes'})
MATCH (patient)-[:HAS_ENCOUNTER]->()-[:PRESCRIBED]->(m:Medication)
RETURN patient.name, collect(DISTINCT m.name) AS medications
Drug Interaction Analysis
// Drug-drug interactions
CREATE (drug1:Drug {name: 'Aspirin'})
CREATE (drug2:Drug {name: 'Warfarin'})
CREATE (interaction:Interaction {severity: 'high', effect: 'bleeding risk'})
CREATE (drug1)-[:INTERACTS_WITH {severity: 'high', effect: 'bleeding risk'}]->(drug2)
// Find patient drug interactions
MATCH (patient:Patient {patientId: 'p001'})-[:PRESCRIBED]->(d:Drug)
WITH patient, collect(d) AS drugs
UNWIND drugs AS d1
UNWIND drugs AS d2
WHERE d1 <> d2
MATCH (d1)-[r:INTERACTS_WITH]->(d2)
RETURN d1.name AS drug1, d2.name AS drug2, r.effect AS interaction
Clinical Trial Analysis
// Map clinical trial eligibility
CREATE (trial:Trial {name: 'Diabetes Study A', phase: 3})
CREATE (criterion1:Eligibility {criteria: 'Age > 18'})
CREATE (criterion2:Eligibility {criteria: 'HbA1c > 7.0'})
CREATE (patient:Patient {patientId: 'p001', age: 45, hba1c: 8.5})
CREATE (trial)-[:REQUIRES]->(criterion1)
CREATE (trial)-[:REQUIRES]->(criterion2)
// Find eligible patients
MATCH (trial:Trial {name: 'Diabetes Study A'})
MATCH (patient:Patient)
WHERE patient.age > 18 AND patient.hba1c > 7.0
RETURN patient.name, patient.age, patient.hba1c
Knowledge Management
Graphs excel at organizing and querying structured knowledge.
Organizational Knowledge
// Company knowledge graph
CREATE (person:Employee {name: 'Alice', role: 'Engineer'})
CREATE (skill:Skill {name: 'Python', category: 'programming'})
CREATE (project:Project {name: 'API Redesign'})
CREATE (doc:Document {title: 'API Specification'})
CREATE (person)-[:HAS_SKILL]->(skill)
CREATE (person)-[:WORKED_ON]->(project)
CREATE (project)-[:HAS_DOCUMENTATION]->(doc)
// Find experts for a topic
MATCH (expert:Employee)-[:HAS_Skill]->(skill:Skill {name: 'Python'})
RETURN expert.name, expert.role
// Find who knows what
MATCH (person)-[:HAS_SKILL]->(skill)
WITH skill, collect(person) AS experts
RETURN skill.name, size(experts) AS expertCount
Semantic Search
// Concept relationships
CREATE (concept1:Concept {name: 'Machine Learning'})
CREATE (concept2:Concept {name: 'Neural Networks'})
CREATE (concept3:Concept {name: 'Deep Learning'})
CREATE (concept1)-[:RELATED_TO {relationship: 'parent'}]->(concept2)
CREATE (concept2)-[:RELATED_TO {relationship: 'parent'}]->(concept3)
// Find related concepts
MATCH (c:Concept {name: 'Deep Learning'})-[:RELATED_TO*1..2]-(related)
RETURN DISTINCT related.name
Master Data Management
Graphs naturally model master data relationships.
Customer 360 View
// Customer data consolidation
CREATE (customer:Customer {customerId: 'c001'})
CREATE (person:Person {name: 'John Doe', ssn: '123-45-6789'})
CREATE (email:Email {address: '[email protected]'})
CREATE (phone:Phone {number: '555-1234'})
CREATE (account:Account {accountNumber: 'A12345'})
CREATE (customer)-[:LINKED_TO]->(person)
CREATE (person)-[:HAS_EMAIL]->(email)
CREATE (person)-[:HAS_PHONE]->(phone)
CREATE (customer)-[:OWNS]->(account)
// Find all related data for customer
MATCH (c:Customer {customerId: 'c001'})-[*1..2]-(related)
RETURN c.customerId, collect(DISTINCT related)
Supply Chain
// Supply chain network
CREATE (supplier:Supplier {name: 'Component Corp'})
CREATE (manufacturer:Manufacturer {name: 'Assembly Inc'})
CREATE (warehouse:Warehouse {name: 'West Warehouse'})
CREATE (retailer:Retailer {name: 'Store 123'})
CREATE (product:Product {name: 'Widget X'})
CREATE (supplier)-[:PROVIDES]->(component:Component)
CREATE (component)-[:SHIPS_TO]->(manufacturer)
CREATE (manufacturer)-[:PRODUCES]->(product)
CREATE (product)-[:STORED_AT]->(warehouse)
CREATE (product)-[:SHIPPED_TO]->(retailer)
// Trace product origin
MATCH (product:Product {name: 'Widget X'})
MATCH path = (product)<-[:PRODUCES|PROVIDES|STORED_AT*1..]-(origin)
RETURN origin.name AS source, type(last(relationships(path))) AS relationship
Best Practices Summary
From these use cases, several patterns emerge:
- Start with clear questions: Define what you want to find before modeling
- Model facts as relationships: Transactions, interactions, dependencies
- Use labels for filtering:
Person:Employee:Engineerfor type hierarchy - Leverage GDS for analytics: PageRank, community detection, similarity
- Combine with other data: Neo4j complements, doesn’t replace, other databases
Conclusion
Neo4j powers production applications across virtually every industry. The use cases demonstrated here show common patterns: social network analysis, fraud detection through connection patterns, recommendation engines, infrastructure dependency mapping, healthcare relationships, and knowledge management. These patterns form the foundation for building robust graph applications.
With this article, we’ve completed the Neo4j tutorial series covering basics, operations, internals, trends, AI applications, and production use cases. You now have comprehensive knowledge to design, implement, and operate Neo4j in your own applications.
Comments