Skip to content
ImagineWorld

Graph Databases

node_idnode-book_building-knowledge-graphs_chapter-03-graph-databases
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleGraph Databases
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In our book Knowledge Graphs: Data in Context for Responsive Businesses (O’Reilly), we said that knowledge graphs predate modern graph data technology. In fact, the concept of knowledge graphs appeared alongside the Semantic Web, before the term graph database had been coined.

More recently, graph databases and graph processing have become a significant trend in contemporary business systems. We’ve observed a correlation between the renewed interest in knowledge graphs and the widespread emergence of graph databases and graph data science tools. In a sense, modern graph technology has put knowledge graphs within practical reach of many organizations, rather than being mostly confined to academia.

This chapter will introduce you to graph databases at a basic practitioner level. It shows you how to use a graph database and, in particular, how to use a query language to store and query knowledge graphs. It also shows you how graph databases work and why they are significantly more performant for knowledge graph workloads than other data technologies.

This is an important chapter, but it is not intended to be comprehensive. Instead, it gives you the sufficient exposure to be able to work through the solutions contained in the rest of this book. If you’re interested and looking for more in-depth information, there are many good books on the topic such as Graph Databases by Ian Robinson, Jim Webber, and Emil Eifrem (O’Reilly).

Building an Embedded Graph Database with Rust

Section titled “Building an Embedded Graph Database with Rust”

While standalone graph databases like Neo4j are incredibly powerful for enterprise workloads, there are times when your architecture demands a tightly coupled, embedded solution. If you are building a high-performance local application, a microservice, or a decentralized tool, you might want the power of a knowledge graph without the overhead of managing a separate database server.

For developers working in Rust—a language prized for its performance and memory safety—you can build a highly capable embedded graph database by combining two excellent crates: petgraph and redb.

In this architecture, petgraph serves as the high-performance, in-memory compute and traversal engine (your query layer), while redb acts as the embedded, ACID-compliant key-value store (your storage layer).

To understand how this works, we need to apply the mechanical sympathy we discussed earlier. A graph consists of nodes and relationships (edges). To persist this in a key-value store like redb, we can design two tables:

  1. A Nodes Table: Maps a unique Node ID (an integer) to serialized node properties.
  2. An Edges Table: Maps a composite key of (Source Node ID, Target Node ID) to serialized relationship properties.

When the application starts, it reads these tables from redb to construct a petgraph::Graph in memory. Queries and traversals are executed at lightning speed using petgraph’s $O(1)$ index-free adjacency. When data is modified, the application writes the serialized updates back to redb using ACID transactions.

Figure 3-17. The architecture of a custom embedded graph database using petgraph and redb.

To implement this, you will need the petgraph crate for the graph structure, redb for storage, and serde with bincode for fast binary serialization of your properties.

First, let’s define the organizing principle (our schema) using Rust’s expressive enum types. This ensures our graph data is strictly typed.

use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum NodeData {
Person { name: String, age: Option<u8> },
Place { city: String, country: String },
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum EdgeData {
LivesIn { since: u16 },
Friend,
}

Next, we define our database logic. We will create a database file, define our redb tables, and write a function to persist our petgraph structure to disk.

use petgraph::graph::{Graph, NodeIndex};
use redb::{Database, TableDefinition};
use std::error::Error;
// Define redb tables.
// Nodes table: Key is u32 (Node ID), Value is a byte array (Bincode serialized NodeData)
const NODES_TABLE: TableDefinition<u32, &[u8]> = TableDefinition::new("nodes");
// Edges table: Key is a tuple of (Source ID, Target ID), Value is a byte array (EdgeData)
const EDGES_TABLE: TableDefinition<(u32, u32), &[u8]> = TableDefinition::new("edges");
pub fn persist_graph(
db: &Database,
graph: &Graph<NodeData, EdgeData>
) -> Result<(), Box<dyn Error>> {
// Begin an ACID transaction
let write_txn = db.begin_write()?;
{
// Open the tables
let mut nodes_table = write_txn.open_table(NODES_TABLE)?;
let mut edges_table = write_txn.open_table(EDGES_TABLE)?;
// 1. Persist Nodes
for node_idx in graph.node_indices() {
let weight = &graph[node_idx];
let serialized_node = bincode::serialize(weight)?;
nodes_table.insert(node_idx.index() as u32, serialized_node.as_slice())?;
}
// 2. Persist Edges
for edge_idx in graph.edge_indices() {
let (source, target) = graph.edge_endpoints(edge_idx).unwrap();
let weight = &graph[edge_idx];
let serialized_edge = bincode::serialize(weight)?;
let edge_key = (source.index() as u32, target.index() as u32);
edges_table.insert(edge_key, serialized_edge.as_slice())?;
}
}
// Commit the transaction to disk safely
write_txn.commit()?;
Ok(())
}

Now we can write the exact same “Rosa lives in Berlin” graph we modeled earlier in Cypher, but natively in Rust. We will construct the graph in petgraph, persist it to redb, and then demonstrate how to execute a graph local query—finding who lives in Berlin.

fn main() -> Result<(), Box<dyn Error>> {
// 1. Initialize the redb database
let db = Database::create("knowledge_graph.redb")?;
// 2. Create an in-memory directed graph using petgraph
let mut graph = Graph::<NodeData, EdgeData>::new();
// Add nodes
let rosa = graph.add_node(NodeData::Person {
name: "Rosa".to_string(),
age: None
});
let berlin = graph.add_node(NodeData::Place {
city: "Berlin".to_string(),
country: "DE".to_string()
});
// Add relationships
graph.add_edge(rosa, berlin, EdgeData::LivesIn { since: 2020 });
// 3. Persist the graph to disk
persist_graph(&db, &graph)?;
println!("Graph successfully persisted to redb!");
// 4. Querying the graph (Compute Layer)
// Let's find who lives in Berlin.
// In petgraph, we can iterate over edges directed toward the Berlin node.
let mut residents_of_berlin = Vec::new();
// petgraph allows us to traverse incoming edges to the 'berlin' node
let mut incoming_edges = graph.neighbors_directed(berlin, petgraph::Direction::Incoming);
while let Some(neighbor_idx) = incoming_edges.next() {
if let NodeData::Person { name, .. } = &graph[neighbor_idx] {
residents_of_berlin.push(name.clone());
}
}
println!("People living in Berlin: {:?}", residents_of_berlin);
// Output: People living in Berlin: ["Rosa"]
Ok(())
}

By combining petgraph and redb, you achieve a system that adheres to the fundamental principles of graph databases:

  • Fast Traversals: petgraph provides the $O(1)$ index-free adjacency required for deep, performant queries in memory.
  • Safety and Durability: redb provides the write-ahead log and ACID transactional guarantees to ensure your knowledge graph survives crashes and power failures.
  • Mechanical Sympathy: Because you control the serialization and the data structures, you can optimize memory layouts specifically for your domain, avoiding the overhead of parsing generic query languages if your use case demands extreme throughput.

While you lose the convenience of the Cypher query language and out-of-the-box visualization tools provided by Neo4j, you gain a statically typed, dependency-free, microsecond-latency embedded database that compiles down to a single binary. For Rust practitioners building high-performance systems at the edge, this is an incredibly potent approach to managing knowledge graphs.

For most knowledge graph developers (and even some users), the majority of interactions with the database will be via the Cypher query language. Cypher is a declarative, pattern-matching query language, originally created by Neo4j but now implemented by several other systems and currently under standardization by the International Organization for Standardization (ISO) as GQL (Graph Query Language, or “SQL for Graphs” informally) at the time of writing.

Cypher’s primary design goal was to be humane and expressive. Its creators saw that people are quite comfortable drawing diagrams with labeled arrows and boxes in drawing tools like Microsoft Visio. Even more importantly, people are comfortable reading those diagrams. Having learned from hard experience with database query languages like SQL and SPARQL, the creators of Cypher reasoned that a good graph query language should be predominantly visual, like a drawing tool. Correspondingly, a visual notation for graphs is at the heart of Cypher.

Don’t worry; being visual doesn’t mean you have to be good at graphics! Being visual means that the structure of queries visually resembles the knowledge graph structure in a way that is intuitive. This is best demonstrated with an example. You might remember the small graph in Figure 3-1, which you first saw in Chapter 1. It shows a group of friends and friends of friends along with some data about where they live.

Figure 3-1. A graph representing people, their friendships, and their locations

Looking at the node representing Rosa in Figure 3-1, you can represent her and her connections as ASCII art with no loss of fidelity. As an example, you can capture the semantics of “Rosa lives in Berlin” with the pattern ( :Person {name: 'Rosa'} )-[:LIVES_IN]->( :Place {city: 'Berlin', country: 'DE'} ), where:

  • The items in () parentheses represent nodes.
  • The :Person and :Place text represents labels on those nodes.
  • The -[:LIVES_IN]-> arrow syntax is a relationship named LIVES_IN between people and places.
  • The {name: 'Rosa'} and {city: 'Berlin', country: 'DE'} are key-value properties that can be stored on nodes (and relationships).

Now, if you prepend CREATE to that pattern, you’ll have a valid Cypher query as shown in Example 3-1.

Example 3-1. Using Cypher’s CREATE keyword to insert a subgraph

CREATE ( :Person {name: 'Rosa'} )-[ :LIVES_IN {since:2020} ]-> ( :Place {city: 'Berlin', country: 'DE'} )

In Example 3-1 the graph structure is very clear. Nodes are represented by parentheses (), which look like circles in ASCII art. Next, there are labels for the nodes like :Place and :Person, which indicate the role those nodes play in the graph (places and people in this case). Nodes can have zero or more of these labels.

Labels group nodes together by role. When a node is created with a label, it is added to the index for that label. Most of the time, you won’t notice these indexes, but the database query planner uses them to make your queries faster. Node labels add fidelity to your models and increase performance. There’s a good maxim here: if you know something about your domain, put it in your knowledge graph.

When storing data, the direction of a relationship is mandatory since it creates a correct, high-fidelity model, disambiguating that Rosa lives in Berlin, rather than Berlin living in Rosa. To store data in Neo4j, you can simply type it into the console as shown in Figure 3-2; after all, what you draw is what you store.

Figure 3-2. Using CREATE to insert graph data into Neo4j

Once you’ve loaded some data into the database, you can query it using Cypher’s MATCH keyword. The purpose of MATCH is to compare user-defined patterns against the underlying knowledge graph. You can see this in Figure 3-3, where the pattern MATCH (n) RETURN n asks the database to find any nodes, represented by parentheses (n), and bind those matches to the variable n to be returned to the caller.

Figure 3-3. Using MATCH to find all items in the database

Importantly, you can traverse a relationship in either direction at the same constant cost. This is a fundamental tenet of the labeled property graph model. In practice it means that the latency of a query is proportional to how much of a knowledge graph you search. Latency is not simply a function of the size of the graph.

The default view in Figure 3-3 also expands any relationships between the nodes matched, so you can treat this query as “show me the whole graph.” For large graphs, this is impractical and usually undesirable, so often you’ll append LIMIT plus a positive integer value to limit the number of records returned, just like in SQL.

Avoiding Duplicates When Enriching a Knowledge Graph

Section titled “Avoiding Duplicates When Enriching a Knowledge Graph”

If you want to grow your graph, you need to create more nodes and relationships. Naively, you might think that just by using CREATE you can build a large graph, but CREATE always creates new data. If you run the code in Figure 3-2 again and refresh the graph display, you will see more than one Rosa node and more than one Berlin node, as shown in Figure 3-4.

Figure 3-4. Using CREATE always inserts new records in the database

Sometimes you do want to CREATE new records, but often you don’t want duplicates in your data. Take a step back, clean up the database, and start again. To remove records from the database, Cypher supports DELETE, which removes the matched records or cleanly aborts if that would leave any relationships dangling. It also has a specialized DETACH DELETE, which removes a matched node and its associated relationships, shown in Example 3-2.

Example 3-2. Using Cypher DELETE and DETACH DELETE

MATCH (n) DELETE n // Deletes nodes
// Cleanly aborts if it leaves relationships dangling.
MATCH ()-[r:LIVES_IN]->() // Deletes LIVES_IN relationships between any nodes
DELETE r
MATCH (n) DETACH DELETE n // Deletes all nodes and any relationships attached,
// effectively deleting whole graph.

Reset the database by issuing the command MATCH (n) DETACH DELETE n. The first time around, since you know that CREATE will always insert new records, you can use Cypher’s MERGE keyword, which inserts records only if the entire pattern does not already exist.

First, create a graph where Karl lives in London: MERGE (:Person {name:'Karl', age:64})-[:LIVES_IN {since:1980}]->(:Place {city:'London', country:'UK'}). Since there are no records in the database, this MERGE acts like a CREATE, and as you would expect, two nodes and a single relationship are persisted in the knowledge graph, as shown in Figure 3-5.

Figure 3-5. MERGE behaves like CREATE when no matching data exists in the database

Now you can see what happens when you MERGE Fred, who also happens to live in London. If you type MERGE (:Person {name:'Fred'})-[:LIVES_IN]->(:Place {city:'London', country:'UK'}), you might expect the database to create a new node to represent Fred and connect it via a new LIVES_IN relationship to the existing node representing London. But, surprisingly, that is not what happens.

MERGE is subtle. Its semantics are a mix of MATCH and CREATE insofar as it will either match whole patterns or create new records that match the pattern in its entirety. It will never partially MATCH and partially CREATE a pattern. As such, in Figure 3-6 what happens is that MERGE cannot fully match the pattern (:Person {name:'Fred'})-[:LIVES_IN]->(:Place {city:'London', country:'UK'}), so it creates that pattern instead, resulting in an unwanted duplicate London node (and no connection between Fred and Karl).

Figure 3-6. MERGE can’t wholly MATCH the pattern on existing data, so it acts like CREATE

You’re not too far into creating your data model, so the quickest thing is to type MATCH (n) DETACH DELETE n, which clears out the whole graph. This time around, think more carefully about the data model. Clearly, there should be only one London, UK, and many people can live there. Also clearly, other places called London (e.g., London, Ontario, in Canada) exist and should be allowed. You can constrain the data model to support the existence of a single London, UK, node after which any updates that try to create additional identical nodes will be (cleanly and safely) rejected.

Create a constraint using:

CREATE CONSTRAINT no_duplicate_cities FOR (p:Place) REQUIRE (p.country, p.city) IS NODE KEY

This statement declares that Place nodes need a unique composite key composed from a combination of city and country properties. Composite constraints are available in Neo4j Enterprise Edition, which is available for free for non-production use as part of Neo4j Desktop. In turn, this ensures the coexistence of London, UK, and London, Ontario, in the database but prevents duplicates of them (and any other city and country combination).

Now that you have a constraint in place, you can go back to thinking about how you’d like to connect both Karl and Fred to the node representing London, UK. To do so, you have to decompose this into three distinct steps:

  1. Create or find a node representing London.
  2. Create or find a node representing Karl and connect it to London.
  3. Create or find a node representing Fred and connect it to London.

Recall that MERGE has the semantics that it exclusively creates or matches patterns in the graph. The MERGE statements in Example 3-3 are executed as part of a single transaction and so will be applied (or rejected) atomically. Moreover, because of the uniqueness constraint, the database won’t accept duplicate Place nodes and will abort any transactions that try to create them.

Example 3-3. Multiline MERGE query

MERGE (london:Place {city:'London', country:'UK'}) // Creates or matches a node to represent London, UK
// Binds it to variable "london"
MERGE (fred:Person {name:'Fred'}) // Creates or matches a node to represent Fred
// Binds it to variable "fred"
MERGE (fred)-[:LIVES_IN]->(london) // Create or match a LIVES_IN relationship between the fred and london nodes
MERGE (karl:Person {name:'Karl'}) // Creates or matches a node to represent Karl
// Binds it to variable "karl"
MERGE (karl)-[:LIVES_IN]->(london) // Create or match a LIVES_IN relationship between the karl and london nodes

If you run the code in Example 3-3 on a clean database, you can then run MATCH (n) RETURN (n) to see all of its contents. What you get is a graph like Figure 3-7.

Figure 3-7. Correct multiline MERGE protected by unique constraints

As developers of knowledge graphs, you have to understand Cypher at a reasonable level. Sometimes queries are typed in the command line, usually for prototyping or ad hoc queries that are outside the normal application workload. Most queries are hosted inside apps that interact with the knowledge graph. Queries are parameterized and sent by the app across the network to be evaluated by the database, just like any relational or NoSQL database. The deployment architecture for graph databases is the same as any other database. It’s the data model that sets graph databases apart from other technology.

By repeatedly following the same pattern using MERGE, you can build large knowledge graphs that capture your domain in high fidelity, as shown in Figure 3-8.

Figure 3-8. A small social graph in Neo4j

Of course, since you are interacting with a database, you can update and enrich the data in your knowledge graph after it has been created. For example, you can add a property that sets Rosa’s date of birth:

MATCH (p:Person)
WHERE p.name = 'Rosa'
SET p.dob = 19841203

Equally, you can remove properties (without deleting the associated node or relationship):

MATCH (p:Person)
WHERE p.name = 'Rosa'
REMOVE p.dob

REMOVE can also be used to strip a label from a node:

MATCH (p:Person)
WHERE p.name = 'Rosa'
REMOVE p:Person

At this point, you’ve learned to store data in your knowledge graphs along with some rudimentary querying. It’s time to expand your skills with queries that are bound to known nodes in the graph.

Now that you can store data in your knowledge graph like in Figure 3-8, you can turn your attention to querying it. Queries are written using Cypher and follow very similar patterns to the way you stored nodes, relationships, and properties.

The heart of a Cypher query is the MATCH clause, as you have already seen with the pattern MATCH (n) RETURN (n). MATCH is used to ask the database to find records in the knowledge graph which match a particular pattern. Using MATCH, you can specify parts of the graph that you know, binding the pattern to parts of the graph that exist, and leave other parts unbound for the database to find. As a simple example, you could ask the question “Who lives in Berlin?” as shown in Example 3-4. This is called a graph local query because it is bound to a specific part of the graph—in this case, the node representing Berlin.1

Example 3-4. Who lives in Berlin?

MATCH (p:Person)-[:LIVES_IN]->(:Place {city:'Berlin', country:'DE'})
RETURN (p)

The query in Example 3-4 is quite readable even if you’re new to Cypher. It starts with MATCH, which tells the database that you want to find patterns. The pattern of interest has some parts that you know exist in the knowledge graph and leaves some parts for the query to find. Specifically, the pattern (:Place {city:'Berlin', country:'DE'}) will match the node representing Berlin, and -[:LIVES_IN]-> will match incoming LIVES_IN relationships to that Berlin node. This is a loose pattern since no properties are specified, but it will still match correctly in your knowledge graph as it stands. The (p:Person) part of the pattern will match any Person nodes in the graph and bind those matches to variable p for later use. When taken together, the pattern asks the database to find any matching patterns where any Person node has an outgoing LIVES_IN relationship to the specific Place node representing Berlin.

Finally, the query returns any Person nodes that have been matched as part of this pattern by RETURN (p), which results in just the node representing Rosa, as shown in Figure 3-9.

Figure 3-9. Results showing that only Rosa lives in Berlin

This query provides a small amount of useful information from the social graph. But that query is quite shallow since it only considers paths of length 1, starting from the node representing Berlin and matching only its immediate neighbors.

More often than not, you’ll want to explore deep into a knowledge graph to find insight. Fortunately, this is simple to do in Cypher and computationally cheap to execute in Neo4j. To demonstrate, you can use the social network to find some friends of friends with whom Rosa might want to interact.

In Example 3-5 you start with the node representing Rosa and then look for any Person nodes that are connected to her via two outgoing FRIEND relationships. You can use the variable-length path syntax *2..2 in this example to specify path lengths from 2 to 2 (that is, exactly length 2). Less compactly, you could have written the pattern in full to the same effect: (:Person)-[:FRIEND]->(:Person)-[:FRIEND]->(:Person). These are equivalent, though the shorter version is preferred since it’s more readable.

Example 3-5. Naive friends of friends

MATCH (:Person {name: 'Rosa'})-[:FRIEND*2..2]->(fof:Person)
RETURN (fof)

If you run the query from Example 3-5, you get the slightly puzzling results shown in Figure 3-10.

Figure 3-10. Rosa shouldn’t be considered her own friend of a friend

In Figure 3-10, Rosa appears as a friend of a friend to herself. That doesn’t feel right, and you can find the reason why if you look at the graph in Figure 3-8. Since Rosa is a friend of Karl, and Karl is a friend of Rosa, there is a depth-two path that matches your -[:FRIEND*2..2]-> pattern, from Rosa to Karl and back to Rosa! To avoid including Rosa, you augment your MATCH clause with a WHERE predicate to constrain the search pattern, as shown in Example 3-6.

Example 3-6. Correctly finding friends of friends

MATCH (rosa:Person {name:'Rosa'})-[:FRIEND*2..2]->(fof:Person)
WHERE rosa <> fof
RETURN (fof)

The WHERE rosa <> fof predicate enriches the pattern. Now it only matches when the node representing Rosa is not the same as the node matched, avoiding the Rosa-Karl-Rosa problem you saw earlier.

There are more predicates you can apply using WHERE, including Boolean operations, string matching, path patterns, list operations, property checks, and more, such as:

  • WHERE n.name STARTS WITH 'Ka'
  • WHERE n.name CONTAINS 'os'
  • WHERE NOT n.name ENDS WITH 'y'
  • WHERE NOT (p)-[:KNOWS]->(:Person {name:'Karl'})
  • WHERE n.name IN ['Rosa', 'Karl'] AND (p)-[LIVES_IN]->(:Place {city:'Berlin'})

You’ll see more of these patterns throughout the book.

After adding the predicate into the query, you find that Rosa’s only friend of a friend is Fred (via her friend Karl), shown in Figure 3-11.

Figure 3-11. Fred is Rosa’s only friend of a friend

Following the same query structure, you could just as easily ask, “Who has friends or friends of friends of someone who lives in Berlin?” where you mix relationship types in patterns and increase the depth of the query. This is normal when querying knowledge graphs and easy to express, as shown in Example 3-7.

Example 3-7. Correctly finding friends and friends of friends of someone who lives in Berlin

MATCH (:Place {city:'Berlin'})<-[:LIVES_IN]-(p:Person)-[:FRIEND*1..2]-(f:Person)
WHERE f <> p
RETURN f

In this example, you can see that the friends and friends-of-friends don’t have to live in Berlin themselves. But it would be a simple addition of another WHERE predicate to change the pattern to enforce that, such as:

MATCH (:Place {city:'Berlin'})<-[:LIVES_IN]-(p:Person)
<-[:FRIEND*1..2]-(f:Person)
WHERE f <> p AND (f)-[:LIVES_IN]->(:Place {city:'Berlin'})
RETURN f

In Example 3-7 a single LIVES_IN relationship must be matched from the node representing Berlin to a person, meaning a person who lives in Berlin. Then there is a variable-length path <-[:FRIEND*1..2]- which matches a friend (at depth 1) or a friend of a friend (at depth 2). As previously shown in Example 3-6, you have to ensure that the starting person isn’t counted as their own friend of a friend, and for that you need to add WHERE f <> p.

Expert relational database users might be concerned about a performance hit from this uninhibited increase in depth but shouldn’t be. Unlike similar queries in a relational databases which use recursive joins, the latency of a query in Neo4j is proportional to how many nodes and relationships are visited, rather than proportional to the size of the database. There are no join-bomb problems to be concerned about, and since the cost of traversing a single relationship is very low (on the order of millionths of a second), a great deal of graph search work can be performed very quickly.

Now you have an answer to who has friends or friends of friends who live in Berlin: it’s Karl (Rosa’s friend) and Fred (Karl’s friend), as shown in Figure 3-12.

Figure 3-12. Karl and Fred have friends or friends of friends who live in Berlin

So far, you’ve anchored your queries to specific nodes, such as asking explicitly about Rosa or Berlin. These are called graph local queries and are quite common in practice.

But what if you want to query the whole graph, as is often the case with knowledge graphs? These queries are called graph global. You might want to ask the simple question, “Which are the most popular cities to live in?” In this case, your query pattern isn’t bound to any specific node but instead must consider all cities and their populations. In your query, you don’t specify any particular node as a starting point because you want to process large parts of the knowledge graph (or even all of it).

The Cypher query and results from the very small social network are shown in Figure 3-13. You can see that London is the most popular city in the social network with two people living there, followed by Berlin with one person. Tabular results are used rather than graph visualization since aggregate numerical data is the goal.

Figure 3-13. London is the most popular city in your social network, followed by Berlin

The graph global query in Figure 3-13 is quite readable and in fact is very similar to the graph local queries that you saw earlier. At the start of the query, there is MATCH (p:Place)<-[l:LIVES_IN]-(:Person), which is a familiar pattern by now. You ask the database to match any pattern that has a Place node with an incoming LIVES_IN relationship from any Person node. Whenever the pattern is matched, you can access variables bound to the matched nodes. Place nodes are bound to the variable p and LIVES_IN relationships bound to the variable l where they can be accessed elsewhere in the query.

You don’t strictly need the :Person label in this query since you know that only Place and Person nodes are joined by LIVES_IN relationships. But when querying graphs, if you know something about your graph, explicitly put it in your query. For example, adding the :Person label rather than using an anonymous node () will help the query planner create better query plans, which improves performance and reduces latency. But never leave out the relationship type since that will explode the search space for a query and consequently greatly increase latency.

Following on from the MATCH clause in Figure 3-13, you see RETURN p AS place, count(l) AS rels ORDER BY rels DESC. This takes more unpacking but will be familiar to anyone with experience with SQL. First, RETURN p AS place means that any pattern matches bound to p (Place nodes) will be returned, but instead of being called p in the results (too pithy), results will be called place. Along with place, the query returns the number of LIVES_IN relationships attached to a Place node and with count(l) AS rels where l is matched from the pattern (specifically LIVES_IN relationships) and given the friendly name rels. Since you want popular cities, you’ll need to impose an ordering on results using ORDER BY rels DESC, which says to order the results on the value of the variable rels and return them in descending order (highest first).

Since Figure 3-13 is a very small social network, you don’t need to filter the results. With just two rows of data returned, all that was needed was to make the names a little more friendly and sort the results. But for production databases, full results could be much larger and may not even be helpful (too much data overwhelms the user). Fortunately, Cypher has aggregation functions avg (average), max (maximum), min (minimum), sum, and so forth, along with clauses like SKIP (skip some results) and LIMIT (limit the number of results returned). Using these, you can craft graph global queries that run over very large knowledge graphs and still return compact, pertinent aggregate information to the user.

Like Cypher, Neo4j supports operations on knowledge graphs by calling functions and procedures which implement specific tasks. Invoking them is easy: you use the Cypher CALL syntax followed by the (namespaced) procedure name and any arguments in parentheses.

For instance, an often-used procedure is to examine the schema of the graph. Figure 3-14 shows how to visualize the schema of the social network knowledge graph that you first saw in Figure 3-8.

Figure 3-14. CALL db.schema.visualization() reveals the schema of the underlying knowledge graph

Another commonly used set of procedure calls comes from the APOC library. APOC is a popular library that ships with Neo4j and contains a plethora of useful functionality and shortcuts for operating on knowledge graphs.

APOC is full of useful procedures and functions. It's a good idea to get to know them to avoid reinventing them yourself.

Example 3-8 shows how the apoc.atomic.concat procedure atomically joins property strings together (with no partial results visible).

Example 3-8. Concatenating property strings with APOC

MATCH (p:Person {name:'Fred'})
// Fred becomes Freddy
CALL apoc.atomic.concat(p,"name",'dy')
YIELD oldValue, newValue
RETURN oldValue, newValue;

Invoking functions is similar to invoking procedures, but you don’t need the CALL syntax. Instead, simply insert the function where you’d normally insert a value, as shown in Example 3-9.

Example 3-9. APOC function for date/time conversion

RETURN apoc.date.convert(datetime().epochSeconds, "seconds", "days") as outputInDays;

Using procedures and functions from libraries can remove drudgery and reduce the possibility of errors when using a knowledge graph. Before embarking on something potentially complicated in Cypher, it’s worth checking to see if there’s a procedure that can help.

Supporting Tools for Writing Knowledge Graph Queries

Section titled “Supporting Tools for Writing Knowledge Graph Queries”

There are two more tools you should know to become competent at Cypher. The EXPLAIN and PROFILE keywords help developers understand the performance of their queries, which is especially important as your knowledge graphs become larger.

EXPLAIN provides a visualization of a query plan, guiding the developer toward reducing the amount of data (“DB hits”) flowing through the query. The visualization that EXPLAIN creates, shown in Figure 3-15, is particularly useful for understanding the behavior of larger queries before actually running them.

Figure 3-15. EXPLAIN shows how the query planner thinks the query will execute without actually executing it

PROFILE goes one step further and instruments a running query to see the actual behavior at runtime. Using PROFILE, developers can see how the query behaves when executed on the real knowledge graph and tune it accordingly, as shown in Figure 3-16.

Figure 3-16. PROFILE gives feedback on the actual execution of a query

Careful use of EXPLAIN and PROFILE can significantly boost query performance. For example, if excessive amounts of data (or DB hits) flow from operator to operator, look for opportunities to refactor the query to reduce cardinality earlier. At a macro level, where the visualization shows expensive tasks like scanning, it can indicate a useful index is missing, trading brute-force scans for index lookups. A box at the bottom of each operator shows the time cost of execution. Aim to minimize that, even at the expense of DB hits.

It might seem slightly strange to read about database internals in a book aimed at an important use case.2 You definitely don’t need to be a database engineer to get significant value from knowledge graphs. But this is a good guiding principle:

You don’t have to be an engineer to be a racing driver, but you do have to have mechanical sympathy.

—Jackie Stewart, three-time Formula 1 racing champion

With a little mechanical sympathy, you can design knowledge graphs that will be robust and performant, delighting the users of your systems. Knowing a little about how the database works under the covers will help you to work with the grain, not against it. At the highest level, a graph database performs two functions on behalf of its users:

  • Queries graph data performantly
  • Stores graph data safely

You will see how each of these is implemented (at a high level) in Neo4j so that you can utilize the machinery well and create responsive knowledge graph systems.

For any production system, you need high availability, monitoring, security, online updates, and many other capabilities. It’s safe to say that these exist (albeit at varying levels of maturity) across many of the graph databases available today both in the cloud and on premises.

To query knowledge graphs performantly, a graph database must make traversals—the act of moving from one node across a relationship to another node—fast (for low latency) and cheap (for high concurrent throughput). Accordingly, the way Neo4j stores its data (both on disk and when it resides in RAM) is optimized for graph traversals. Neo4j stores the structure of a graph (nodes and relationships) separately from the property data. The graph structure is stored as fixed-length records: one store for nodes and a similar one for relationships. Multiplying the ID of a record by its size in bytes gives you its offset in the corresponding store file. This pattern is known as index-free adjacency and has been written about in “The Graph Traversal Pattern” (https://oreil.ly/rPmHP) by Marko A. Rodriguez and Peter Neubauer. Index-free adjacency via pointer-chasing is very efficient on modern computers.

It’s noteworthy that there are typically no indexes involved in traversing a graph (unless the query optimizer spots a shortcut that involves indexes). The relationships on a node act as a local “index” that guides the traversal to where it can (legally) go next.

Index-free adjacency is such a powerful property because it gives you $O(1)$ or “constant time” traversals. This means that graph query latency is proportional to the amount of graph traversed, rather than being proportional to the size of the graph. It has the effect that even complex queries tend to run quickly and at low computational cost.

Property storage in Neo4j is different, designed for data flexibility. Since properties can take many forms in knowledge graphs, like strings, numbers, lists, and more, the storage format needs to be accommodating. In Neo4j, properties are maintained in lists of descriptive property records where the head of the list is referenced from the associated node or relationship. Unlike node or relationship stores, property stores are $O(N)$ or “linear time” for reads, meaning that access to a property is proportional to the number of properties stored for that node or relationship. For writes, the property stores remain $O(1)$ since the new property is added to the head of the relationship chain.

One thing that knowledge graph developers should be aware of is the cumulative cost of property access. Though each access itself might be cheap in elapsed time (especially if the data is currently cached in RAM), accessing many properties during traversals adds up. In the case of larger traversals, frequent access to properties can increase latency greatly, up to double according to some practitioners.

Where possible, queries should traverse the graph structure first and then retrieve property data once target nodes and relationships have been found. This ensures that most work is done quickly and cheaply with $O(1)$ operations, with fewer more expensive $O(N)$ operations.

Sometimes you can’t avoid lots of property lookups in your knowledge graph queries, because properties influence how the graph is traversed. While the database can’t do anything about the theoretical cost of those accesses, it can in practice greatly reduce their impact by ensuring that the working set is in the faster parts of the memory hierarchy. Modern computers, of course, have a well-understood memory hierarchy: from disks (including SSDs) being the slowest, through RAM, to CPU caches being the fastest.

Use Modern Hardware

Don’t use spinning disks. The seek time for a fast spinning disk is 5 ms, which is a very long time for computers. During that time, the database could have completed many thousands of traversals instead of waiting for I/O. For any serious project, it’s worth investing in good disks and plenty of RAM to host the data for the best possible performance.

It’s the database management system’s job to ensure that the records needed next by a query are in memory (most of the time) rather than having to go to disk to retrieve them. It uses locality-aware caching strategies to try to ensure that hot data is in a fast part of the memory hierarchy. If this is maintained, the physical cost of accessing any record, including properties, is significantly reduced. To maximize the chances of this working sustainably, a healthy ratio of RAM to data size should be used. For the most demanding use cases, the whole knowledge graph should fit in RAM. With this in mind, sometimes the cheapest and quickest remedy for slow workloads is simply to add more RAM!

To store data safely, Neo4j—like many other databases—has a transactional write channel that provides fault-tolerant writes. This is based on a classic “write-ahead log,” whereby intended updates to the database are first persisted in an ordered fashion on disk before being applied to the knowledge graph. This gives the database the ability to tolerate power cycling. When power is restored, it can recover any transactions that have been cleanly persisted in the log and safely discard those whose data was only partially stored.

Neo4j maintains ACID (atomicity, consistency, isolation, durability) transactions across servers as well as in the single-server case. To do so, it uses an algorithm called Raft that keeps individual transaction logs “tied” together (hence the name).

Atop Raft, Neo4j provides a 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 causal feature is opt-in and transparent but makes working with the database cluster as simple as reasoning about a variable in a programming language.

Making a database fault tolerant is not an easy thing to do, and there are many edge cases. But from the point of view of a knowledge graph user, your data is kept safe from corruption and highly available in the presence of software and hardware faults. A trustworthy, fault-tolerant graph database is the right underlay for knowledge graphs at enterprise scale (and beyond). Having an “operationally boring” graph database leaves you to focus on unlocking the value from your knowledge graphs.

In this chapter, you’ve seen how Cypher queries are a pleasant pattern-matching syntax based on ASCII art. The underlying graph database provides a high-performance platform for storing and querying knowledge graph data.

Using what you’ve learned in this chapter, you can query knowledge graphs performantly and update them safely. But it’s often the case that at least some data for the knowledge graph already exists in other systems. The next chapter discusses methods for importing data into a knowledge graph to use it as a foundation for further enrichment and gaining valuable insight.


[1] The authors work at Neo4j at the time of writing.

  1. Graph local queries may process many or few records; the local element simply states that some parts of the pattern are bound to known nodes or relationships, rather than iterating the whole graph. ↩

  2. If you’re certain that you don’t want to learn how graph databases work, you can skip ahead to Chapter 4. ↩