Graph Algorithms and Analytical Techniques
local graph
Chapter 6 — Graph Algorithms and Analytical Techniques
Section titled “Chapter 6 — Graph Algorithms and Analytical Techniques”Chapter 4: Graph Algorithms and Analytical Techniques
Section titled “Chapter 4: Graph Algorithms and Analytical Techniques”The true power of a graph database is not revealed by simple pattern matching, no matter how sophisticated the Cypher. The moment an organization moves from asking “who is connected to asking “who matters, who belongs, who influences, how are things grouped, what is the cheapest or fastest route, and who should see this product next,” the conversation shifts from retrieval to insight. This is the domain of graph algorithms and analytics.
Neo4j’s Graph Data Science (GDS) library is the most battle-tested, scalable, and feature-complete graph analytics platform in existence. It executes natively inside the database engine, leverages the same index-free adjacency that makes traversal fast, and operates on in-memory projected graphs that can reach hundreds of billions of relationships on commodity clusters. Every major algorithm class centrality, community detection, pathfinding, similarity, link prediction, node embedding, and graph neural networks is available as a production-grade, parallelized procedure.
This chapter teaches these algorithms not as isolated mathematical curiosities but as operational weapons that have detected hundreds of billions of dollars in financial crime, powered recommendation systems serving hundreds of millions of concurrent users, optimized supply chains for global manufacturers, and accelerated drug discovery for pharmaceutical companies. Mastery means understanding when to use which algorithm, how to interpret its scores in the specific business context, how to tune it for performance and accuracy, and how to productionize the results back into the operational graph.
4.1 Centrality Metrics: PageRank, Betweenness, and Closeness
Section titled “4.1 Centrality Metrics: PageRank, Betweenness, and Closeness”Centrality algorithms answer the question “which nodes are most important?” The answer is never absolute; it is always relative to a specific definition of importance.
PageRank – Global Influence and Authority
Section titled “PageRank – Global Influence and Authority”PageRank, originally designed to rank web pages, has become the universal measure of node authority in directed networks. The intuition is beautifully simple: a node is important if it is pointed to by other important nodes. The algorithm models a random surfer who follows outgoing links with probability 1-d and teleports
randomly with probability d (typically 0.85). After convergence, each node’s score is the long-term probability of finding the surfer there.
In real systems, PageRank identifies fraud rings (high-score synthetic identities), influential customers (marketing), critical infrastructure components (IT/OT), and authoritative biomedical entities (knowledge graphs).
cypher
// 4.1.1 Personalized PageRank on a financial transaction graph// First, project a weighted, directed graph in memoryCALL gds.graph.project( 'txGraph', 'Account', { TRANSFER: { orientation: 'NATURAL', aggregation: 'SUM', properties: 'amount' } }, { relationshipProperties: 'amount' })
// Run personalized PageRank seeded from known good accountsCALL gds.pageRank.stream('txGraph', { maxIterations: 40, dampingFactor: 0.85, sourceNodes: gds.util.asNodeList( [nodeId FROM gds.util.nodeId('Account', {accountId: 'KNOWN_GOOD_1'})], nodeId FROM gds.util.nodeId('Account', {accountId: 'KNOWN_GOOD_2'})] )})25 )
26 })
27 YIELD nodeId, score
28 WITH gds.util.asNode(nodeId) AS account, score
29 WHERE score > 0.15
30 RETURN account.accountId AS accountId, score
31 ORDER BY score DESC
32 LIMIT 50;
Commentary: Lines 3–16 create an in-memory projection named txGraph containing only Account nodes and TRANSFER relationships, preserving direction and summing amounts for weighting. Lines 19–26 run personalized PageRank seeded from two known clean accounts critical for fraud detection where global PageRank is polluted by criminal volume. Line 29 filters for anomalously high authority scores that indicate money-mule or layering accounts.
Betweenness Centrality – Bottlenecks and Control Points
Section titled “Betweenness Centrality – Bottlenecks and Control Points”Betweenness measures how often a node lies on the shortest paths between all other pairs. High betweenness nodes are natural control points: removing them fragments the graph.
Use cases include supply-chain risk (single points of failure), telecommunications (critical routers), and fraud (cut vertices that connect otherwise disconnected rings).
cypher
1 // 4.1.2 Betweenness on a supply-chain graph 2 CALL gds.graph.project( 3 ‘supplyChain’, 4 [‘Part’, ‘Supplier’], 5 ‘SUPPLIES’ 6 )
7
8 CALL gds.betweenness.stream(‘supplyChain’, {samplingRatio: 0.3, samplingSeed: 42})
9 YIELD nodeId, score
5 SET a.communitySeed = 999999
6
7 CALL gds.labelPropagation.mutate(‘txGraph’, { 8 mutateProperty: ‘fraudCommunity’, 9 seedProperty: ‘communitySeed’ 10 }) 11 YIELD communityId, nodesCount 12 RETURN communityId, nodesCount ORDER BY nodesCount DESC LIMIT 20;
4.3 Pathfinding Algorithms: Shortest Path, Dijkstra, and A*
Section titled “4.3 Pathfinding Algorithms: Shortest Path, Dijkstra, and A*”Pathfinding is the oldest and most solved problem in graph theory, yet remains critical.
Weighted Shortest Path with Dijkstra
Section titled “Weighted Shortest Path with Dijkstra”cypher
1 // 4.3.1 Cheapest shipping route considering cost and customs delay 2 CALL gds.graph.project( 3 ‘logistics’, 4 ‘Location’, 5 ‘SHIPS_VIA’, 6 {relationshipProperties: [‘cost’, ‘delayHours’]}) 7 ) 8 9 CALL gds.shortestPath.dijkstra.stream(‘logistics’, { 10 sourceNode: gds.util.nodeId(‘Warehouse-NYC’), 11 targetNode: gds.util.nodeId(‘Customer-Berlin’), 12 relationshipWeightProperty: ‘cost’ 13 }) 14 YIELD index, nodeIds, costs
15 RETURN
16 [id IN nodeIds | gds.util.asNode(id).name] AS route,
17 reduce(total = 0, c IN costs | total + c) AS totalCost
18 ORDER BY totalCost ASC LIMIT 5;
A* with Heuristic for Geospatial Routing
Section titled “A* with Heuristic for Geospatial Routing”cypher
1 // 4.3.2 Fastest delivery route using road network + Haversine heuristic
2 CALL gds.shortestPath.astar.stream(‘roadNetwork’, { 3 sourceNode: gds.util.nodeId(‘Pickup-Paris’), 4 targetNode: gds.util.nodeId(‘Drop-Lyon’), 5 latitudeProperty: ‘lat’, 6 longitudeProperty: ‘lon’, 7 relationshipWeightProperty: ‘travelTimeMinutes’ 8 })
9 YIELD path
10 RETURN [node IN nodes(path) | node.address] AS fastestRoute;
4.4 Similarity and Recommendation Algorithms in Neo4j
Section titled “4.4 Similarity and Recommendation Algorithms in Neo4j”Similarity is the foundation of recommendation, deduplication, and anomaly detection.
Node Similarity – Jaccard and Overlap
Section titled “Node Similarity – Jaccard and Overlap”cypher
1 // 4.4.1 Product recommendation via common purchasers
2 CALL gds.nodeSimilarity.stream(‘bipartite’, { 3 topK: 10, 4 similarityCutoff: 0.4 5 })
6 YIELD node1, node2, similarity
7 WITH gds.util.asNode(node1) AS productA,
gds.util.asNode(node2) AS productB, similarity WHERE productA.category = ‘Electronics’ RETURN productA.sku, productB.sku, similarity ORDER BY similarity DESC;
Cosine, Pearson, and Euclidean Similarity on Embeddings
Section titled “Cosine, Pearson, and Euclidean Similarity on Embeddings”When nodes have vector properties (from LLMs, images, etc.):
cypher // 4.4.2 Semantic product similarity using text embeddings CALL gds.similarity.cosine.stream({ nodeProjection: ‘Product’, relationshipProjection: {}, property: ‘embedding’ }) YIELD node1, node2, similarity WHERE similarity > 0.85 RETURN gds.util.asNode(node1).name, gds.util.asNode(node2).name, similarity ORDER BY similarity DESC LIMIT 100;
FastRP – Scalable Node Embeddings for Cold-Start Recommendations
Section titled “FastRP – Scalable Node Embeddings for Cold-Start Recommendations”Fast Random Projection produces dense embeddings in linear time.
cypher CALL gds.fastRP.mutate(‘recommendationGraph’, { embeddingDimension: 256, iterationWeights: [0.8, 1.0, 1.0], normalizationStrength: 0.5, mutateProperty: ‘embedding’ }) YIELD nodePropertiesWritten;
4.5 Advanced Analytics with Graph Data Science Library
Section titled “4.5 Advanced Analytics with Graph Data Science Library”Link Prediction Pipelines
Section titled “Link Prediction Pipelines”Predict missing relationships using topological features.
// 4.5.1 Predict future friendshipsCALLgds.alpha.linkprediction.adamicAdaboost.stream('socialGraph', { topK: 20})YIELD node1, node2, scoreWHERE NOT (node1)-[:FRIEND]-(node2) // exclude existingRETURN gds.util.asNode(node1).name, gds.util.asNode(node2).name, scoreORDER BY score DESC LIMIT 50;Graph Embeddings + Machine Learning
Section titled “Graph Embeddings + Machine Learning”Combine FastRP with scikit-learn or Neo4j’s own node classification.
# 4.5.2 Python pipeline: FastRP + Logistic Regression for fraudfrom neo4j import GraphDatabasefrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionimport numpy as np
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "Mastery2025!"))
# Extract embeddings and labelsquery = """MATCH (a:Account)12 RETURN a.accountId AS id, a.embedding AS embedding, a.isFraud AS label
13 """
14 with driver.session() as session: 15 result = session.run(query) 16 data = [(r[‘id’], np.array(r[‘embedding’]), r[‘label’]) for r in result]
17
18 ids, X, y = zip(*data) 19 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
20
21 clf = LogisticRegression() 22 clf.fit(X_train, y_train) 23 print(f”Accuracy: {clf.score(X_test, y_test):.4f}”)
Graph Neural Networks via GDS
Section titled “Graph Neural Networks via GDS”Neo4j supports native GraphSAGE and node classification.
cypher
1 // 4.5.3 GraphSAGE for node classification 2 CALL gds.beta.graphSage.train(‘heterogeneous’, { 3 modelName: ‘fraudModel’, 4 featureProperties: [‘balance’, ‘txCount’, ‘embedding’], 5 projectedFeatureDimension: 128 6 })
Synthesis and Reflection
Section titled “Synthesis and Reflection”Graph algorithms transform a well-modeled graph from a sophisticated index into a reasoning engine. The practitioner who has mastered this chapter can now:
- Detect influential entities with PageRank even in noisy, directed networks.
- Identify critical bottlenecks with betweenness before they cause outages.
- Uncover hidden communities that no rule or query could surface.
- Compute optimal routes under real-world constraints in milliseconds.
- Deliver personalized recommendations that improve as more data arrives.
- Turn raw topology into dense embeddings that power downstream machine learning.
These capabilities are no longer research prototypes; they are production systems protecting billions in assets and driving billions in revenue. The next frontier, explored in subsequent chapters, is fusing these symbolic algorithms with neural approaches to create truly intelligent graph applications that combine the explainability of classic algorithms with the predictive power of deep learning.
The graph is no longer just data. It is intelligence.