Skip to content
ImagineWorld

Enriching Knowledge Graphs with Data Science

node_idnode-book_building-knowledge-graphs_chapter-06-enriching-knowledge-graphs-with-data-science
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleEnriching Knowledge Graphs with Data Science
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Enriching Knowledge Graphs with Data Science

Section titled “Chapter 6 — Enriching Knowledge Graphs with Data Science”

This chapter will introduce you to graph data science. The aim of graph data science is to gain insight into your knowledge graph using graph algorithms. Towards that goal, you’ll learn about the common types of graph algorithms and the insights they unearth as well as how Neo4j Graph Data Science provides a simple platform for experimenting with, sharing, and productizing graph algorithms. You’ll also learn how to execute graph algorithms on real knowledge graphs and experience how the system does much of the heavy lifting for you.

Like Chapter 3, this chapter is not intended to be comprehensive but rather to give you the foundation to be able to work through the remainder of the book. For those looking for more depth, there are many good books dedicated to specific deep technical topics, like Graph Data Science for Dummies (https://oreil.ly/X8UQc) by Dr. Alicia Frame and Zach Blumenfeld (Wiley).

Graph algorithms yield some insight about a knowledge graph’s structure. That insight could be influential people in a social graph, critical junctions in a rail network, cells of fraudsters, or a common pathogen in a disease pathway. While the design and implementation of graph algorithms is a specialist subject, using them is not. You simply need to understand the purpose of the algorithms and the syntax to execute them over your knowledge graph.

As in Chapter 3 Neo4j has been chosen for graph algorithm examples. It has the most popular and extensive graph algorithms toolkit and is easily accessible to nonspecialists through the Cypher query language.

Neo4j Graph Data Science (https://oreil.ly/uICA_) is easily installed via the Neo4j desktop app (https://oreil.ly/wOYz8). Neo4j Sandbox (https://oreil.ly/ypp9M) is a learning environment for Neo4j that provides access to Neo4j Graph Data Science. Neo4j AuraDS (https://oreil.ly/zQj-8) is graph data science as a service, a companion to the AuraDB graph database service.

You can use any of these to follow the examples in this chapter and undertake your own graph data science work.

Some readers might remember graph algorithms from college, perhaps even with fondness. For others, the notion of graph algorithms may be new. This chapter will start you off gently, with an overview of the different kinds of data processing that you can do on graphs, followed by a deeper dive into how to use some common graph algorithms. You’ll learn how to experiment with those algorithms in a graph data science motion, and how to incorporate them into production systems. By the end of this chapter you’ll feel as comfortable running graph algorithms over large knowledge graphs as you already are running Cypher queries.

There are many graph algorithms from which to choose, each of which performs some computation over a given graph to generate insight from the underlying topology and data. Learning which algorithm to choose for a given situation takes modest effort. The first step is to sort the algorithms into categories to provide a high-level view of what kinds of insights can be computed. From there, you can move to the more detailed step of choosing a specific algorithm.

For the purposes of computing over knowledge graphs, there are three broad categories of algorithms:

Statistical Provides metrics about the graph, such as the number of nodes and relationships, degree distribution of relationships, types of node labels, and so on. These will provide context for interpretation of your results.

Analytical Surfaces significant patterns or latent knowledge over the whole knowledge graph or significant subcomponents.

Machine learning (ML) Uses the results from graph algorithms as features to train machine learning models or uses machine learning to evolve the knowledge graph itself.

This chapter is concerned with using statistical and analytical methods to uncover insight from your knowledge graph, leaving machine learning to its own full chapter in Chapter 7. Within statistical and analytic algorithms, there are five categories that are common to knowledge graph use cases:

Network propagation Understanding how signals propagate through a knowledge graph requires deep path computations. The resulting pathways can identify the spread of disease in a community or supply-chain weaknesses. Correspondingly, the results can be used to optimize for containment or adding redundancy to critical paths.

Influence In current times of near-ubiquitous social media, you are accustomed to the idea of “influencers,” or people whose opinions spread rapidly through the social graph. In graph data science, the goal is more general. Influential nodes act as bridges (and bottlenecks) between subgraphs and are ideally positioned to spread information (or disruption) around the network quickly since they are, on average, close to all the other nodes. A measure of a node’s influence is known as its centrality.

Community detection In the human world, communities are the ties that bind us together. That’s true in the world of graph algorithms too, but to find tightly knit communities, graph algorithms tend to partition groups by looking for weak links to remove. Being able to detect communities in a knowledge graph tells you about related works that you might want to read, fraudsters cooperating to commit financial crimes, or communities where pathogens (including disinformation) will spread quickly.

Similarity When you visualize a knowledge graph, you can often easily spot similar patterns being repeated in the graph. For example, you can see customers with a particular purchase history who would be well served with a particular product recommendation or road intersections associated with abnormal levels of vehicle collisions. But when the graph is large, manual inspection falls short. Similarity algorithms search for known relationships/hierarchies between nodes or common properties on them.

Link prediction Using the existing topology of the knowledge graph with some heuristics (for example, creating triangles), link prediction algorithms can enrich the knowledge graph by computing missing relationships. This is a common use case in social networks where possible friends/followers/contacts can be computed.

Within each of these broad categories, there are usually several different algorithms from which to choose. Each algorithm behaves differently and will typically give different results for the same input. For example, the community detection algorithms Weakly Connected Components (WCC) and Louvain give different results for the same input graph.

The question naturally arises: which should you choose? Often the answer lies in reading the documentation and choosing the algorithm that makes the most sense for your context. Sometimes the answer is to experiment with algorithms and use the one that provides the best answers for your context. But first you need to understand how graph data science functions so that you can experiment with graph algorithms.

Neo4j Graph Data Science is a graph computation framework that is conveniently integrated with the Neo4j graph database. This means you can project data from your knowledge graph stored in Neo4j, then compute an analysis using a graph algorithm (using multiple CPUs). You can subsequently inspect the results from your computation, share it with your coworkers, or even write the result back to the underlying knowledge graph to enrich it. The tight integration between Neo4j Graph Data Science and the graph database removes many operational burdens, allows you to focus on running algorithms, and minimizes data wrangling.

It’s common in industry for some classes of algorithms to run on graphics processing units (GPUs) to take advantage of the benefits of GPU architecture: high parallelism and high bandwidth between processing elements. However, GPUs are best suited when an algorithm can be expressed as a linear algebra problem, which is by no means universal (or trivial). Currently, Neo4j Graph Data Science is highly optimized for CPU and RAM. It provides best-in-class performance for the widest range of algorithms without the inconvenience of specialized hardware, and it typically outperforms GPU-based solutions (since not all graph algorithms can be expressed as linear algebra problems, which are efficiently executable on GPUs).

Neo4j Graph Data Science offers a broad range of high-performance, parallelized algorithms. You choose an algorithm based on the kind of insight you need or run algorithms with Cypher procedure calls, just like in “Calling Functions and Procedures”. The way Neo4j Graph Data Science works in combination with your knowledge graph is shown in Figure 6-1.

Figure 6-1. The components involved in running a graph algorithm over a knowledge graph in Neo4j

Figure 6-1 shows the four distinct phases of executing a graph algorithm over your knowledge graph:

Read projected graph Choose the parts of the graph that you are interested in processing and create a projection. This can be a subgraph, specific labels and relationship types, patterns from a Cypher query, or even the whole knowledge graph.

Load projected graph Export the graph projection into a compact, in-memory format ready for parallel processing.

Execute algorithm Run the algorithm with parameters you choose.

Store results Write the results back into the knowledge graph (e.g., enriching nodes) or compute results that can be sent to downstream systems or the calling user.

The graph projection phase loads (part of) your knowledge graph into main memory, in a compressed format. Being in memory ensures high performance because of locality benefits whereby the neighbors of any given node are also in memory and are therefore fast to access during processing. This means that for very large graphs, you may have to scale up your RAM. For parallel algorithms, you can scale up CPU cores too.

The opposite approach, scale-out, is initially appealing. Adding more CPU cores and RAM by adding servers is a classic approach pioneered by Apache Hadoop. But now you have nonuniform architecture where any node’s neighbors are likely to be on remote servers, accessible at a far greater time cost than local memory. In practice, distributed graph processing is inefficient since the locality benefits of being in a single large memory space are absent. Instead of a simple pointer dereferencing, you now have network operations.

While there is active research work on distributed graph processing and the underlay required to make it efficient (e.g., software-defined high-performance networks), at time of this writing, the scale-up approach used by Neo4j Graph Data Science remains the fastest and most practical method. Furthermore, its simplicity means it’s often cheaper than running large clusters of compute servers. In the longer term, as research matures into technology, it’s possible this situation might change, and when it does, as a Graph Data Science user you should be insulated from those implementation details while reaping any accrued performance benefits.

Example 6-1 shows an example of enriching a knowledge graph by computing over it. In this case, it shows how to project a social network of Person nodes and FRIEND relationships from a graph of people and places, then executes a betweenness centrality algorithm over the resulting graph projection to calculate the most influential person.

Example 6-1. Running Graph Data Science from Cypher

CALL gds.graph.project.cypher(
'gds-example-graph',
'MATCH (p:Person) RETURN id(p) AS id',
'MATCH (p1:Person)-[:FRIEND]->(p2:Person) RETURN id(p1) AS source, id(p2) AS target, "FRIEND" AS type'
);
CALL gds.betweenness.write('gds-example-graph',{
writeProperty: 'betweennessCentrality'
});

The query consists of four key elements:

Name the graph projection Here it is gds-example-graph, and that projection will be stored under that name in the graph catalog for access by subsequent computations.

Node query Select the nodes that will be included in the projection. Neo4j Graph Data Science has multiple ways of doing this, including simply by node label. The most flexible choice is a Cypher projection that allows you to specify Cypher code to select nodes of interest. The node IDs have to be returned as a column called id as part of the contract for projections. In Example 6-1, all Person nodes are selected.

Relationship query Select the relationships that will be included in the projection. Since this is a Cypher projection, you must supply a Cypher query that identifies the relationships of interest. Importantly, these relationships must connect to nodes from the node projection (or it will fail). The start, end, and type of each relationship must be returned as source, target, and type columns as per the contract for relationship projections.

Execute the algorithm The line gds.betweenness.write means that the betweenness centrality algorithm will be called and that it will write back its results into the graph, as opposed to streaming them back to the caller (gds.betweenness.stream) or enriching only the projection (gds.betweenness.mutate). Its parameters are the projection on which to operate (gds-example-graph) and the name of the node property into which results will be written (betweennessCentrality). Note that once a projection is created, you can run the algorithm as many times as you need against that projection without having to re-create it.

Betweenness centrality computes the number of paths that pass through a given node to establish the node’s importance in the graph. If you run the algorithm on the small social network from Figure 3-8, then the knowledge graph will be enriched. This is shown in Figure 6-2.

Figure 6-2. Small social network with computed betweenness centrality scores written to the Person nodes

In Figure 6-2, it’s clear that Karl has the highest betweenness centrality. Since Karl is the connecting node between Rosa and Fred, without him the whole of the social network would collapse. This is very apparent in Figure 6-3.

Figure 6-3. Visualizing the impact of centrality scores with Neo4j Bloom

In Neo4j’s Bloom visualization tool shown in Figure 6-3, you can configure the size (or color) of a node to be based on a property. This means, for example, that you could make nodes bigger based on their betweenness centrality score so that the higher the centrality, the bigger the node is represented. It makes visualizations much more information rich and valuable for the end user.

Betweenness centrality isn’t the only thing you can use to enrich your knowledge graphs. You can choose from 65+ algorithms, including pathfinding, PageRank, Louvain, and so forth. Each of them is executed just like Example 6-1, so experimenting to find the right insight for your domain is operationally straightforward at least.

On a small knowledge graph, the betweenness centrality computation finishes instantaneously. For modest graphs of tens to hundreds of thousands, you probably won’t notice the execution time either. But for very large knowledge graphs on a scale of millions or billions, the computation might take several seconds or even minutes (depending on the algorithm, projection, and hardware).

In practice, this isn’t a problem since you tend to enrich knowledge graphs periodically. In those situations where you want fast feedback, such as during experimentation, then choose smaller projections or select servers with more RAM and CPU.

Part of any data scientist’s job is to experiment. If you’re going to learn graph data science, you’ll also need to learn good experimental habits, and that requires the ability to iterate quickly over hypotheses. Neo4j Graph Data Science contains the tools you need to competently experiment with algorithms over knowledge graphs.

However, the architecture presented in Figure 6-1 shows a very database-centric view of knowledge graph processing. With all those components, it’s possible to become lost in complexity when all you’re really trying to do is experiment by running algorithms over your knowledge graph. Fortunately, there is Python tooling that can abstract some of the details of databases and allow you to work at a much higher level of abstraction. After all, viewing the world as Python objects is much more idiomatic for data scientists.

Your graph data science toolkit comprises Neo4j and Graph Data Science (of course), the Neo4j Graph Data Science Python driver, and Jupyter Notebook or something similar. Since you’ve gotten this far in the book, it’s likely you have already installed Neo4j and Graph Data Science.

The next steps are to install the Pythonic API for Graph Data Science and, if necessary, Jupyter Notebook or something similar. Assuming you have Python 3 installed, then use pip to install the other dependencies. pip install graphdatascience installs the Pythonic API for Graph Data Science, and pip install notebook installs Jupyter Notebook support.

Now that you have your tooling, you can start experimenting. The following examples are all based on the rail network in Great Britain. It’s large, but not too large, highly interconnected, and very much a real-world use case, making it ideal for the budding graph data scientist to explore.

You can download the source data for this experiment from https://github.com/jbarrasa/gc-2022.

To begin, load the data that represents the railway stations and the tracks between them. That data is stored in CSV files, one for stations (nr-stations-all.csv) and one for tracks linking them (nr-station-links.csv). The code for how to load that data using Python is shown in Example 6-2.

Example 6-2. Loading CSV data into Neo4j in Python

from graphdatascience import GraphDataScience
# Connect to the database
host = "bolt://127.0.0.1:7687"
user = "neo4j"
password= "yolo"
gds = GraphDataScience(host, auth=(user, password), database="neo4j")
# Load stations as nodes
gds.run_cypher(
"""
LOAD CSV WITH HEADERS FROM "nr-stations-all.csv" AS station
CREATE (:Station {name: station.name, crs: station.crs})
"""
)
# Load tracks between stations as relationships
gds.run_cypher(
"""
LOAD CSV WITH HEADERS FROM "nr-station-links.csv" AS track
MATCH (from:Station {crs: track.from})
MATCH (to:Station {crs: track.to})
MERGE (from)-[:TRACK {distance: round( toFloat(track.distance), 2 )}]->(to)
"""
)
gds.close()

The Python code in Example 6-2 does three things:

Creates a connection to the database Creating an instance of the GraphDataScience class provides authenticated access to the database management system that will host the underlying knowledge graph. Pay attention to the network endpoint and username/password combinations.

Loads nodes into the graph to represent stations Use gds.run_cypher, which allows the data scientist to run arbitrary Cypher queries. In this case, it uses a LOAD CSV command just like in Chapter 4. The command takes data from a CSV file (ignoring the headers) and uses Cypher CREATE to populate the knowledge graph with Station nodes with their common name (name) and their official unique code (crs).

Links nodes with relationships to represent tracks Again, gds.run_cypher is used to execute a LOAD CSV job. Here the database looks up the from and to nodes for a piece of track using the crs unique codes for the stations. It then uses MERGE to create a single relationship of type TRACK between those stations while adding a distance property to those relationships. The distance property is stored as a floating point value rounded to two decimal places.

Nowhere in Example 6-2 did you have to deal with drivers, sessions, or other technical database things. You just used a Python object in your code.

Once the data is loaded into the graph, you could simply poke around the data using Cypher queries using the Python API and run_cypher. That’s handy if you’re a keen Python programmer, but it’s nothing radically different from Chapter 3. However, the Python API also allows you to create projections and execute algorithms over them. It’s time to run those algorithms.

One of the most common queries for travel networks is to find the shortest (or cheapest) path between two stations. It’s straightforward to do this from Python with Graph Data Science. First, you need to create a projection from the railways knowledge graph, creating a domain-specific in-memory graph suitable for algorithmic computation. In this case, the projected graph is topologically similar to the original knowledge graph, but the nodes contain less data, just common station names, and distances between them are stored as a relationship property. If you later find you need more data in a projection, simply create that new richer projection where it will be added to the graph catalog alongside your existing projections. Example 6-3 shows how to use the Python API to create a Cypher projection (the other projection methods are also supported from Python).

Example 6-3. Using the Python API for Graph Data Science to create a graph projection from the railway knowledge graph

from graphdatascience import GraphDataScience
host = "bolt://127.0.0.1:7687"
user = "neo4j"
password= "yolo"
gds = GraphDataScience(host, auth=(user, password), database="neo4j")
gds.graph.project.cypher(
graph_name='trains',
node_spec='MATCH (s:Station) RETURN id(s) AS id',
relationship_spec=
"""
MATCH (s1:Station)-[t:TRACK]->(s2:Station)
RETURN id(s1) AS source, id(s2) AS target, t.distance AS distance
"""
)
gds.close()

In Example 6-3 a GraphDataScience object is instantiated to obtain an authenticated connection to the database hosting the knowledge graph. Then, gds.graph.project.cypher is used to create a projection called trains that will be stored in the graph catalog for later use. The content of the trains projection is defined by node_spec and relationship_spec properties. The node_spec parameter is a MATCH clause that returns the node IDs of all stations. The relationship_spec parameter is a MATCH clause that returns the node IDs of source and target stations, along with a distance property for the TRACK relationships that will connect stations in the projection. Once executed, the projection is stored in the graph catalog ready for experimentation.

The Python code for running a shortest-path algorithm is shown in Example 6-4. It follows the same pattern as the other examples in terms of setting up a connection to the database. It then sets up parameters for the experiment by using find_node_id and a Cypher expression to find the IDs of the nodes representing Birmingham New Street and Edinburgh stations, which are stored in the variables bham and eboro, respectively.

The code then runs one of the shortest-path algorithms, Dijkstra’s algorithm in this case. The algorithm is set up to work on the projection called trains and takes bham and eboro as its sourceNode and targetNode parameters. It also takes a value for the relationshipWeightProperty parameter, which is the distance property that the algorithm will use to compute path costs.

Example 6-4. Using the Python API for Graph Data Science to compute the shortest path between Birmingham New Street and Edinburgh

from graphdatascience import GraphDataScience
host = "bolt://127.0.0.1:7687"
user = "neo4j"
password= "yolo"
gds = GraphDataScience(host, auth=(user, password), database="neo4j")
bham = gds.find_node_id(["Station"], {"name": "Birmingham New Street"})
eboro = gds.find_node_id(["Station"], {"name": "Edinburgh"})
shortest_path = gds.shortestPath.dijkstra.stream(
gds.graph.get("trains"),
sourceNode=bham,
targetNode=eboro,
relationshipWeightProperty="distance"
)
print("Shortest distance: %s" % shortest_path.get('costs').get(0)[-1])
gds.close()

Once the algorithm is executed, you’ll see that the shortest path between Birmingham New Street and Edinburgh is printed out: Shortest distance: 298.0. You can also visualize this path in the Neo4j Browser, as shown in Figure 6-4.

Figure 6-4. Shortest path between Birmingham New Street and Edinburgh

Curious readers might be wondering about the choice of railway stations in this example. As it happens, one of the authors (Jim Webber) grew up in Birmingham, England, which was one reason that Birmingham New Street was an obvious choice. Edinburgh just happens to be a beautiful city.

But Birmingham is geographically interesting.1 It’s in the center of England, and Birmingham New Street is a busy hub station that serves routes across Great Britain, including routes that intersect Edinburgh in the Scottish lowlands. As such, you might suppose that Birmingham New Street is the most critical station on the rail network in Great Britain. Based on that supposition, you might also advocate for significant investment in the station and its surrounding track to ensure that failures are few and gracefully handled.

But what if the supposition is wrong? Fortunately, you have the tools at your disposal to quickly verify that hunch.

The trains projection contains all the data you need to analyze the situation. To verify (or debunk) Birmingham New Street’s importance in the rail network, you’re going to have to compute its centrality. Happily, that is very straightforward, as you can see in Example 6-5.

Example 6-5. Using the Python API for Graph Data Science to compute centrality scores for all railway stations in Great Britain

from graphdatascience import GraphDataScience
host = "bolt://127.0.0.1:7687"
user = "neo4j"
password = "yolo"
gds = GraphDataScience(host, auth=(user, password), database="neo4j")
graph = gds.graph.get("trains")
result = gds.betweenness.stream(graph)
highest_score = result.sort_values(by="score", ascending=False).iloc[0:1].get('Node')
n = gds.run_cypher(f"MATCH (s:Station) WHERE ID(s) = {int(highest_score)} RETURN s.name")
print("Station with highest centrality: %s" % n["s.name"][0])
gds.close()

Running the code in Example 6-5 reveals Station with highest centrality: Tamworth, which isn’t what was expected from an informal understanding of the system. In fact, Tamworth’s centrality score is 1,967,643 while Birmingham New Streets, is almost eight times lower at 254,706.

Now you know that it is Tamworth, just a few miles away from Birmingham, that has the highest centrality score and so the greatest impact on the rail network in the case of failures. If you are in charge of rail transport policy, that’s where you might start.

Graph Data Science Reveals Counterintuitive Results

Section titled “Graph Data Science Reveals Counterintuitive Results”

A puzzling fact about the result in Example 6-5 is that high-centrality Tamworth has far lower passenger numbers at 1.2 million per year versus Birmingham New Street’s 47 million (plus 7 million passenger interchanges). In fact, Birmingham New Street is the eighth busiest station in Great Britain and the busiest station outside London. This would seem to be opposed to the finding that Tamworth is the most important.

In reality, two things might be occurring. The first is that the centrality computation didn’t weight passengers or train routes, only connected track. From the point of view of the physical network, Tamworth really is important. Second, network effects are real. It’s quite likely that if infrastructure at Tamworth fails, it will impact the large volume of passengers at Birmingham New Street and stations further afield, as faults ripple through the network.

Real life isn’t always as simple as a single algorithmic score. Graph data scientists should always look to refine their problems with richer data or more accurate projections, or they should be prepared to reformulate their hypotheses and bring more data and algorithms to bear. Fortunately, the experimental motion of Python and Graph Data Science allows for rapid reevaluation of test cases, giving you more opportunity to iterate toward a good answer.

The setup in “Experimenting with Graph Data Science” is great for experimentation, but there comes a time when you’re happy with your projections and algorithm choices, and you want to move into production. At this point, you’re no longer in the world of Python objects and Jupyter Notebooks but squarely in the domain of production data engineering.

A common setup to support knowledge graphs and graph algorithms is to separate your physical servers by role, providing physical isolation for different workloads. Neo4j supports the concept of primary and secondary servers for this purpose. Primary servers are responsible for transaction processing, keeping your knowledge graph clustered for scale and fault tolerance. They also typically serve Cypher queries.

In principle, primaries can also run graph algorithms, but doing so would cause contention between the computational workload of the algorithms and the ongoing database workload. Instead, consider deploying secondary instances for data science. Secondary instances have looser time guarantees about updates compared to primaries since they receive their updates asynchronously rather than transactionally. They don’t slow down transaction processing.

It is also normal to size secondaries differently from primaries and perhaps even to each other depending on the intended workload. For example, you could decide that your primary instances are equipped with large RAM and high I/O but modest CPU since you intend to run database queries and transactions that are rarely CPU bound. Your secondaries would then be configured with multiple fast CPUs and high RAM to enable fast parallel computation using graph algorithms or to support graph global queries, as shown in Figure 6-5.

Figure 6-5. Primaries host your knowledge graph, and secondaries are used for compute-intensive graph data science

The infrastructure of Neo4j clusters allows you to tag servers with their intended roles so that users of the system send their jobs to the most appropriate physical server for their needs. All this is simple and mostly transparent.

To be clear, Neo4j makes operating hybrid transactional and analytics processing (HTAP) for knowledge graphs very straightforward. It’s a single cluster with the same data throughout. There’s no need for ETL or online analytical processing (OLAP) cubes or other complex data engineering.

But there will be times when you want guarantees about a secondary’s freshness before you run a graph algorithm on it. In Chapter 3 you read that Neo4j provides an optional causal barrier, which means that users of the database always see at least their own writes, even with servers spread out over a wide area network. This casual barrier applies across both primaries and secondaries and for data science just as much as transactional workloads. Using the causal barrier is easy, as you can see in Example 6-6 (shown in Rust).

Example 6-6. Bookmarks work on secondaries, which are good workhorses for Graph Data Science

// Using the neo4rs Rust driver
let mut txn = graph.start_txn().await?;
txn.execute(
query("CREATE (user:User {userId: $userId, passwordHash: $passwordHash})")
.param("userId", user_id)
.param("passwordHash", password_hash)
).await?;
txn.commit().await?;
// Bookmark is the ID of the transaction you just committed.
let bookmark = graph.last_bookmark().await;

The first part of the causal barrier in Example 6-6 is where last_bookmark() is called. This gives you the ID of the transaction you just committed. You can subsequently present that ID to the database to ensure no operations will proceed unless that transaction has been processed by the receiving server (including secondaries), as shown in Example 6-7.

Example 6-7. Using a Bookmark to enforce a causal barrier

// Start a new transaction passing the previous bookmark
let mut txn = graph.start_txn_with_bookmarks(vec![bookmark]).await?;
let result = txn.execute(
query("MATCH (user:User {userId: $userId}) RETURN user")
.param("userId", user_id)
).await?;

In Example 6-7, when opening the next transaction with start_txn_with_bookmarks, you provide the bookmark object from Example 6-6. Now the operation will not proceed until that transaction is processed at the current server. You will always see at least your own writes, even on secondaries.

The other place where production data science tends to differ from the experimental phase is what you choose to do with the results. For experiments, capturing results in a notebook (physical or digital) is often preferred. For production use, you need to utilize the results to improve the system.

Recall from Example 6-5 that results of the centrality computation were streamed back to the Python client using result = gds.betweenness.stream(graph) and then printed to the console. If those results were useful, then you’d like to capture them in a way that can be operationalized. Fortunately, this is straightforward; you simply swap out the stream method for mutate, which updates the projection with the results, or write, which enriches the underlying knowledge graph (irrespective of where the computation executed).

Example 6-8 shows how this is achieved.

Example 6-8. Using the Python API for Graph Data Science to compute centrality scores for all railway stations in Great Britain

from graphdatascience import GraphDataScience
host = "bolt://127.0.0.1:7687"
user = "neo4j"
password = "yolo"
gds = GraphDataScience(host, auth=(user, password), database="neo4j")
graph = gds.graph.get("trains")
result = gds.betweenness.write(gds.graph.get("trains"), writeProperty="betweenness" )
total_stations = gds.run_cypher("MATCH (s:Station) RETURN count(s) AS total_stations")
print(f'Total number of stations: {total_stations.iloc[0][0]}')
processed_stations = gds.run_cypher(
"""
MATCH (s:Station)
WHERE s.betweenness IS NOT NULL
RETURN count(s) AS stations_processed
""")
print(f'Number of stations with betweenness score: {processed_stations.iloc[0][0]}')
gds.close()

If you run the code in Example 6-8, it performs the centrality calculation, but instead of just sending results to the console, it writes them back to the underlying knowledge graph, enriching it for future use cases, such as graph feature engineering for ML. A message is also written to the console so that you can verify that the knowledge graph has been enriched:

Total number of stations: 2593
Number of stations with betweenness score: 2593

As you can see, moving from exploratory graph analysis to data science to refining experiments to production readiness is straightforward. Even readers who are not data scientists by training should be able to make good progress following this pattern. As the underlying knowledge graph gets richer (and of course is kept up to date by frequent application of algorithms), the possibilities for deep understanding of data emerge.

In this chapter, you’ve learned (or perhaps even relearned) about graph algorithms. Far from being dull and computerish, experimentation with graph algorithms surfaces quantifiable insight. You’ve also seen that very little coding or data engineering is needed.

In the next chapter, you’re going to mix graph algorithms with ML. You’ll build better predictive models with graph features created by algorithms and use graph-native ML so that algorithms directly enrich the knowledge graph.


  1. But also has an undeserved reputation among the British for being boring. As the heart of the industrial revolution, it was the Silicon Valley of its day, and much of that heritage remains. ↩