Integrating Knowledge Graphs with Information Systems
local graph
Chapter 5 — Integrating Knowledge Graphs with Information Systems
Section titled “Chapter 5 — Integrating Knowledge Graphs with Information Systems”Knowledge graphs are useful systems in their own right. But the real power of knowledge graphs is when they are integrated with other systems. When integrated, a knowledge graph will enrich other systems and in turn be enriched by them in a virtuous cycle.
There are several ways to integrate knowledge graphs into your data fabric, so this chapter will guide you through some popular choices. These range from client-side database drivers, (custom) functions and procedures, and APIs to streaming middleware and finally ETL (extract, transform, load) tools. For each of these, you’ll be provided with a technical architecture sufficient to give direction and further pointers so that you can tackle implementation confidently.
Towards a Data Fabric
Section titled “Towards a Data Fabric”Data fabrics are a general-purpose, organization-wide data access layer that offers a connected view of the data in the underlying systems. A data fabric abstracts away details of how data is accessed in third-party systems and allows your users to access that data transparently via the knowledge graph. When supporting a knowledge graph, the data fabric provides an enterprise-wide index over systems so that relevant data can be consumed as a dependable layer of master data with golden records for important entities like customers, products, and events.
While the bytes-over-the-wire part of the data fabric is achieved with traditional integration methods, the informational model coalesces around a knowledge graph at the heart of the fabric. The knowledge graph’s job is to provide a sophisticated index to curate data across silos irrespective of how the data is physically stored in those silos as relational tables or NoSQL keys and values, as shown in Figure 5-1.
Figure 5-1. Using a knowledge graph for data integration
The knowledge graph in Figure 5-1 provides a curated index across multiple underlying data systems (which are typically unaware of the data fabric). It acts as an entry point so that when a client application or user requests “Give me the customer John Smith from Seattle,” it can follow the relationships in the graph to leaf nodes, which redirect to records in other systems.
In Figure 5-1, customer records are kept in a document database, the product catalog is stored in another graph database, and billing information is stored in a relational database. All of these are accessed transparently through an integration layer, using techniques as part of the data fabric. The knowledge graph retrieves data from the underlying systems and combines it into a holistic set of data for the client, without the client having any knowledge that multiple backend systems were used.
Data architects often turn to graphs because they are flexible enough to accommodate multiple heterogeneous representations of the same entities as described by each of the source systems. With a graph, it is possible to associate underlying records incrementally as data is discovered. There is no need for big, up-front design, which serves only to hamper business agility. This is important because data fabric integration is not a one-off effort, and a graph data model remains flexible over the lifetime of the data domains.
To improve the quality and correctness of the data and increase interoperability across the enterprise, you can overlay an organizing principle, such as an ontology, taxonomy, or enterprise canonical model, atop the integrated data and present it to consumers as a knowledge graph. The organizing principle makes it possible to validate data across systems and check for inconsistencies or violations of the semantics of the data.
Curating your data with a knowledge graph supported by a data fabric has significant benefits. Characteristics like node degrees, neighborhood information, and centrality metrics can be used to build sophisticated and effective data integrations. For example, you can define a matching rule as follows: two nodes represent the same product and therefore can be deduplicated, if their names have a strong string similarity (say over 95%) and they have identical clustering coefficients (see Chapter 6). The result is that data owners get significantly improved matching rates when aligning multiple data sources using a knowledge graph.
But to achieve these goals, you need to deploy a data fabric to integrate your knowledge graph with underlying systems. It’s time to examine some implementation options.
The Database Driver
Section titled “The Database Driver”The most commonly used way of integrating with a knowledge graph is through a driver. A driver is a piece of client-side middleware that sits underneath your application code and makes network calls to the knowledge graph, integrating the two parts of the system.
In fact, you’ve already seen drivers in action in this book. Recall that in Chapters 3 and 4 you saw multiple examples of interacting with the database using the Cypher query language via the Neo4j Browser tool. Neo4j Browser provides a REPL (read-evaluate-print loop) console through which you can enter Cypher queries for evaluation by the database.
It might look as if the Browser is directly connected to the database, but that’s not the case. There’s a connection string which the Browser uses to establish an instance of a Neo4j driver through which it communicates over the network (even if it’s the local network interface) to the Neo4j server that hosts the knowledge graph. Neo4j drivers implement a client-server architecture between a knowledge graph and its consuming systems (including human users), as shown in Figure 5-2.
Figure 5-2. A high-level view of the client-server architecture connecting the knowledge graph to other systems via the network
In the general case, a Neo4j driver is a piece of client-side middleware that allows your application or microservice code to connect to the Neo4j server which hosts your knowledge graph. In the case of the Neo4j Browser, the driver happens to be written in JavaScript. But there are numerous other drivers from which to choose based on your language and platform preferences.
Neo4j Drivers
Section titled “Neo4j Drivers”Neo4j provides several language drivers for common programming languages and frameworks:
- Rust
- Serde and optional Object-Graph Mapper (Rust)
- .NET
- JavaScript
- Python
- Go
In addition, there are several well-maintained drivers written by the Neo4j community:
- Ruby
- PHP
- Erlang/Elixir
- Perl
- C/C++
- Clojure
- Haskell
- R
- Py2Neo Object-Graph Mapper (Python)
You choose the driver for your preferred language (or closest, such as the Rust driver for other systems programming environments). Each driver provides the same functionality: connecting your application code to Neo4j (including clusters of Neo4j servers and the AuraDB cloud service) via the Bolt protocol or HTTP.
The best way to understand how to use Neo4j drivers to interact with your knowledge graph is by example. Example 5-1 shows a typical example using the Neo4j Rust driver, neo4rs (noting that other languages follow a similar pattern).
Example 5-1. Using the Neo4j Rust driver
use neo4rs::{Graph, query};use std::sync::Arc;
pub struct RustDriverExample { // 1. Driver (Graph) objects are expensive. // You typically want just one of these for your whole application lifetime. graph: Arc<Graph>,}
impl RustDriverExample { pub async fn new(uri: &str, user: &str, pass: &str) -> Result<Self, neo4rs::Error> { let graph = Arc::new(Graph::new(uri, user, pass).await?); Ok(Self { graph }) }
pub async fn find_friends(&self, name: &str) -> Result<(), neo4rs::Error> { // 2. Sessions and transactions are cheap. Use them whenever you need them. // 3. Telling the driver whether the query updates the graph helps routing decisions. let mut txn = self.graph.start_txn().await?;
// 4. Parameters are good let mut result = txn.execute( query("MATCH (a:Person)-[:FRIEND]->(b:Person) WHERE a.name = $name RETURN b.name") .param("name", name.to_string()) ).await?;
while let Ok(Some(row)) = result.next().await { let friend_name: String = row.get("b.name").unwrap(); println!("Friend: {}", friend_name); }
txn.commit().await?; Ok(()) }}
#[tokio::main]async fn main() -> Result<(), neo4rs::Error> { let example = RustDriverExample::new("127.0.0.1:7687", "neo4j", "password").await?; example.find_friends("Rosa").await?; Ok(())}There are four important things in Example 5-1 to keep in mind when you’re using any of the Neo4j drivers:
- Driver objects are expensive. You should only have one of these for the lifetime of the application connecting to the knowledge graph. It’s expensive because it deals with setting up (and tearing down) network connections, including authentication. You certainly don’t want to be paying that price on a per-query basis.
- Session/Transaction objects are cheap. They’re also quite sophisticated, including various async APIs to help smooth processing on behalf of clients. They also support causal boundaries (also known as bookmarks) so that clients always see at least their own writes even on a globally distributed cluster.
- Tell the receiving server whether a query is read-only or read/write. This helps a cluster make better routing decisions about where queries should be processed to maintain high throughput.
- Parameterize all queries. Parameterized queries don’t need to be reparsed or have new query plans generated by the database. They’re faster than just using literal strings across the network. Instead of concatenating strings like
MATCH ( :Person {name: 'Karl'}), useMATCH (n:Person {name: $name})and send parameters separately. Parameterizing queries also helps protect against injection attacks.
From Neo4j 5 onward, Cypher will try to automatically parameterize queries, even if they are not constructed that way. It’s still good practice to identify all parameters to your query, in case the parser cannot.
The short example in Example 5-1 shows how easy it is to build applications or microservices to interact with the knowledge graph over the network. But you can also use logic that is deployed on the database server itself.
Graph Federation with Composite Databases
Section titled “Graph Federation with Composite Databases”Neo4j Composite Databases enable you to bring together multiple graph data sources and provide a single unified point of access to all of them. This technique, called federation, does not physically combine the databases but creates a virtual composite. The consumer application is unaware that data is drawn from multiple sources.
Figure 5-3 shows three independent graph databases, one with a product catalog and two with sales information. The two sales databases use the same graph data model, but one of them contains orders from Europe, Middle East, and Africa (EMEA) customers, and the other contains orders from Asia-Pacific (APAC) customers.
Example 5-2. A logical database called globalsales integrates multiple physical databases
// Run in Cypher shell or one line at a time in Neo4j browserCREATE DATABASE db1;
CREATE DATABASE db2;
CREATE COMPOSITE DATABASE globalsales;
CREATE ALIAS emeasales FOR DATABASE db1;
CREATE ALIAS apacsales FOR DATABASE db2;Neo4j Composite Databases allow you to retrieve data from all federated databases with a single Cypher query. The query in Example 5-3 returns all customers who placed more than 100,000 orders.
Figure 5-3. Graph federation with Neo4j Composite Databases
To create a composite database using Neo4j Composite Databases, add code like Example 5-2 to the neo4j.conf file. This example creates a composite database called globalsales.
Example 5-3. A single Cypher query retrieves all customers who placed more than 100,000 orders
UNWIND ['globalsales.apac', 'globalsales.emea'] AS gCALL { USE graph.byName(g) MATCH (c:Customer)-[:PURCHASED]->(o:Order)-[:ORDERS]->(p:Product) WITH c, sum(o.quantity * o.unitPrice) AS totalOrdered WHERE totalOrdered > 100000 RETURN c.customerID AS name, c.country AS country, totalOrdered}RETURN name, country, totalOrderedThe query in Example 5-3 federates EMEA and APAC sales from separate underlying graphs to provide an aggregated view to the consuming application. You can easily extend that to include the product catalog. In Example 5-4, the query returns a list of global customers who have purchased products of a given category, such as Beverages.
Example 5-4. A query that returns a list of global customers who purchased beverages from multiple underlying graphs
CALL { USE globalsales.catalog MATCH (p:Product{discontinued:false})-[:PART_OF]->(:Category{categoryName: 'Beverages'}) RETURN COLLECT(p.productID) AS pids}WITH pids, [g IN fabricnw.graphIds()] AS gidsUNWIND gids AS gidCALL { USE globalsales.graph(gid) MATCH (c:Customer)-[:PURCHASED]->(o:Order)-[:ORDERS]->(p:Product) WHERE p.productID IN pids RETURN distinct c.customerID AS name, c.country AS country, p.productName AS product}RETURN name, country, productAside from the graph itself, the most compelling aspect of Example 5-4 is that the implementation complexity is abstracted away from the user. The fact that (at least) two underlying graph databases are composed to a single virtual database is handled by Neo4j Fabric, leaving you to focus on your domain.
Server-Side Procedures
Section titled “Server-Side Procedures”Client-server interactions using Cypher and Neo4j drivers are commonplace. But sometimes your needs aren’t wholly met by that paradigm and you need specific logic to run close to the knowledge graph on the server (like a stored procedure in SQL databases).
Neo4j has an excellent library of functions and procedures that come with the database (e.g., for managing users and roles, visualizing the inferred knowledge graph schema, or doing data science operations, as you’ll see in Chapter 6). APOC, as you saw in Chapter 4, has lots of different functions and procedures you can call on to help with common and not-so-common cases.
Since knowledge graphs are better when they are integrated with other systems, why not use APOC to make calls into a SQL database to enrich the knowledge graph data at query time? Using the pattern shown in Example 5-5, you can extract data from a SQL database as part of a Cypher query and have that data mixed in with the knowledge graph data. No copying required.
Example 5-5. Calling to a SQL database from a procedure
CALL apoc.load.driver("com.mysql.jdbc.Driver");
WITH "select firstname, lastname from employees where firstname like ? and lastname like ?" AS sql
CALL apoc.load.jdbcParams("northwind", sql, ['F%', '%w'])YIELD row
MATCH (p:Person {firstname: row.firstname, lastname: row.lastname})-[:WORKS_FOR*1..3]->(boss:Person)RETURN (boss)The Cypher code in Example 5-5 loads a SQL database driver into Neo4j and then uses it to access a SQL database called northwind. The code runs a SQL query against northwind, which retrieves the first and last names of employees in the database and returns them as nodes in Cypher. From here, you can mix those nodes into regular Cypher queries on the graph. In this case, the query tries to find who the person from the SQL database works for in the knowledge graph, up to three levels up.
Using procedures, you can enrich the knowledge graph with data from other databases at query time without having to move or copy that data from its source system. No need to rip and replace, but you do need to take the latency (and reliability) of the remote call into consideration since it will add to the latency of your knowledge graph query.
Example 5-6 shows an interoperability procedure from the APOC library to extract some data from MongoDB (a store which itself has no knowledge graph capabilities). The intent is to enrich your knowledge graph with data from the other system. The CALL deals with connecting to the remote database, and returns data from a MongoDB query in a format suitable for further Cypher processing. Specifically, take the id of a document in MongoDB and MATCH it to a node in the graph. With that data, you then search at depth 1 or 2 out from the matching experiment node in the knowledge graph to try to find any environmental contaminants that may be present. The query then returns those contaminants to the caller.
Example 5-6. Using APOC to access data in a different database
CALL apoc.mongodb.find('mongodb://mongo:neo4j@mongo:27017', 'results', '2022-02-22-wetlab', {'status': "failed"}, null, null)YIELD value AS failed_experimentsMATCH (:Experiment { id: failed_experiments.id})-[*1..2]->(environmental_factors)RETURN environmental_factors.contaminants AS contaminantsNow that you have seen the principle established, it’s not hard to imagine how you might also bring in data from other sources, not just other databases. APOC has a simple solution to load JSON data from a file or web page (e.g., a file stored in Amazon S3), which you can see in Example 5-7.
Example 5-7. Calling a JSON Web API from a procedure
WITH "https://example.org/karl.json" AS urlCALL apoc.load.json(url) YIELD valueUNWIND value.products AS product
WITH product
MATCH (k:Person {name:'Karl'})MERGE (k)-[:BOUGHT]->(:Product {name:product.name, price:product.price, description:product.description})Like the equivalent SQL example in Example 5-5, Example 5-7 shows how you can consume JSON-formatted data easily in the context of a query running on a knowledge graph. In this specific example, you use that JSON data to enrich the underlying graph via MERGE with people who have bought products.
Data Virtualization with Neo4j APOC
Section titled “Data Virtualization with Neo4j APOC”Sometimes you won’t have the luxury of combining underlying graph databases into a single virtual knowledge graph. If your underlying data is in different nongraph sources, like time-series data, clickstream data, or log data, you’re going to have to use a different approach.
Fortunately, the APOC library supports the definition of a catalog of virtual resources. A virtual resource is an external data source that Neo4j can use to query and retrieve data on demand, presenting it as virtual nodes enriching the data stored in the graph, as shown in Figure 5-4.
Figure 5-4. Virtual nodes and relationships mapping to external data sources
Figure 5-4 shows the architecture for the system. The library call sits as an intermediary between the end user and the databases they want to use, which include a Neo4j graph, a CSV file, and a relational database. As queries are executed on the graph database, the APOC library retrieves data from the CSV file and relational database and presents it as virtual nodes and relationships to the query engine where they are mixed in with the native graph data from Neo4j.
Bear in mind that accessing data from CSV files or other databases will usually have higher latency than accessing the local knowledge graph. Figure 5-4 and similar are useful insofar as they hide the difference between graph and nongraph data and allow seamless enrichment of your knowledge graph without having to take copies of other data. But you can’t hide latency, so be judicious how you use it.
As an example, using the approach in Figure 5-4, you can build a digital twin of a telecom network, as shown in Example 5-8. The graph contains a representation of the network, with all of the physical, logical, and virtualized devices and the connections between them. The Cypher fragment in Example 5-8 shows how the digital twin’s graph is built.
Example 5-8. Building a digital twin of a telecom network
// network topology creation// adding network devicesMERGE (nsn:NetworkDevice { name: "Nogent sur Marne", nd_ld: "N08", pos: point({latitude:2.46995, longitude:48.834374}), gtype: 1, code: "nog-1" });MERGE (ms:NetworkDevice { name: "Montrouge Sud", nd_ld: "N11", pos: point({latitude:2.316613, longitude:48.805473}), gtype: 1, code: "mon-3"});// ...// adding links between network devicesMATCH (nsm:NetworkDevice { code: "nog-1" })MATCH (ms:NetworkDevice { code: "mon-3" })MERGE (nsm)-[:LINK]->(ms)SET l = { linkId: "s1_385/ol", bundleId: "s1_128/ob", linkType: "OTN Line", capacity: 1920 };If you run the code in Example 5-8, it creates the top-level graph structure for the digital twin. Figure 5-5 shows a visualization of its initial state.
Figure 5-5. Digital twin of a telecom network
Though the knowledge graph in Figure 5-5 is functionally incomplete, it is already of some use. For example, the Cypher query shown in Example 5-9 retrieves the two endpoints of a failing network link.
Example 5-9. Retrieving the endpoints for a failing link
MATCH (aend:NetworkDevice)-[l:LINK]->(zend:NetworkDevice)WHERE l.linkId = "s1_385/ol"RETURN aend.code, zend.codeFor a simple root cause analysis, you correlate the failure of a link with the recent performance metrics of the two endpoints. But this is a static view of the system. To make a functionally complete system, you need to add real-time performance metrics for each network device to enrich the model. But those performance metrics aren’t in the graph, and probably shouldn’t be since they are rapidly changing counters in hardware deployed into the physical telecommunications network.
In this case, you use a procedure from APOC to combine data from an external system (a SQL-queriable database) with the knowledge graph’s topological data. The SQL query in Example 5-10 returns the performance metrics for the last 24 hours. It queries the device_perf table in the metrics_collector database, which is indexed by device_id and by timestamp.
Example 5-10. A SQL query that returns performance metrics for the last 24 hours
SELECT latency, packetloss, packetdupl, jitter, throughputFROM device_perfWHERE device_id = $device_id AND timestamp > now() - interval '1 day';You can create a virtualized resource to handle this integration between the knowledge graph and the other database. To do so, invoke the apoc.dv.catalog.add stored procedure, then specify the SQL query to be executed. Creating the virtualized resource is shown in Example 5-11.
Example 5-11. Creating a virtualized resource using APOC
CALL apoc.dv.catalog.add("metrics-by-device-id", { type: "JDBC", url: "jdbc:postgresql://localhost/metrics_collector?user=bob&password=bobby", labels: ["Town", "PopulatedPlace"], query: "SELECT latency, packetloss, packetdupl, jitter, throughput FROM device_perf WHERE device_id = $device_id AND timestamp > now() - interval '1 day';", desc: "french towns by department number"})Now that you have created a virtualized resource, you can use it. Example 5-12 shows how to use the virtualized resource created in Example 5-11 to retrieve data from the metrics database on demand.
Example 5-12. Querying the virtualized resource using APOC
MATCH (aend:NetworkDevice)-[l:LINK]->(zend:NetworkDevice)WHERE l.linkId = "s1_385/ol"WITH aend, zendCALL apoc.dv.query("metrics-by-device-id", {device_id: aend.nd_id}) YIELD nodeRETURN aend.code, properties(node), zend.codeThe query results combine data from the graph (topology information) with data retrieved on demand from the performance metrics database. The knowledge graph acts as a logical integration layer (a data fabric) offering users and consumer apps a unified view of the network and real-time metrics in the form of a digital twin. While you’ll be aware of the technical implementation, users just see a single holistic knowledge graph with transparently up-to-date data.
Custom Functions and Procedures
Section titled “Custom Functions and Procedures”The existing library of Cypher procedures is extensive, both the built-in Neo4j procedures and the APOC library. But sometimes you need to operate on your knowledge graph in a highly domain-specialized fashion, which isn’t covered by Cypher or other procedure libraries.
Fortunately, Cypher is extensible. It allows both user-defined functions and user-defined procedures, so you can build functions and procedures to suit your own exacting needs.
User-defined functions and procedures in Neo4j do not carry the same stigma as stored procedures in SQL. You write Rust code (or via FFI bindings), which can be tested independently of the database. You can adopt the same version control and build practices that you use for your solution as a whole so that the custom code is robust.
In Figure 5-6 you can see how user-defined functions and procedures (including the built-in ones) fit into (a simplified version of) the architecture. Those user-defined functions and procedures are written in Rust or another compiled language and invoked from Cypher.
Figure 5-6. User-defined functions and procedures in the graph stack
Unlike plain Cypher where the Cypher query is executed against the kernel (kernel level) API from the Cypher runtime, user-defined functions and procedures are defined using the database’s Rust API (a friendlier level of abstraction). By decorating your custom functions and procedures with the correct annotations and implementing the correct interfaces implied, you can create a procedure or function with arbitrary functionality.
For example, you might want a procedure that inspects, computes over, or even updates the knowledge graph. To demonstrate how straightforward it is to build such a procedure, Example 5-13 shows a simple algorithm for counting the degree (number of attached relationships) of all nodes in the knowledge graph.
Example 5-13. A custom procedure for creating a histogram of node degree (Rust conceptually via FFI/Plugins)
use std::collections::BTreeMap;// Conceptual graph API for custom proceduresuse graph_db_api::{Context, Node, Stream};
pub struct NodeDegree { pub degree: u64, pub number_of_nodes: u64,}
#[procedure(name = "getNodeDegrees")]#[description("Get degrees of all nodes in the knowledge graph")]pub fn get_node_degrees(ctx: &Context) -> Stream<NodeDegree> { // We use a BTreeMap to keep the degrees sorted automatically let mut node_degrees: BTreeMap<u64, u64> = BTreeMap::new();
// Iterate through all nodes in the graph for node in ctx.graph().get_all_nodes() { let degree = node.get_degree(); *node_degrees.entry(degree).or_insert(0) += 1; }
// Build the stream to return back to the Cypher engine let mut stream = Stream::new(); for (degree, count) in node_degrees { stream.push(NodeDegree { degree, number_of_nodes: count, }); }
stream}Most of the code in Example 5-13 is logic that counts relationships incident on nodes. The more interesting parts are where the procedure binds to the underlying knowledge graph. For instance, you get access to the underlying database that hosts the knowledge graph by using the injected Context API, which ensures that a reference to the database management system is available to your procedure before your code runs. You declare the entry point to your procedure with the #[procedure] macro with its friendly name getNodeDegrees and provide a friendly description with #[description]. Finally, remember that you must return a Stream of a record type, like NodeDegree in this case.
The procedure in Example 5-13 is global, as it touches all nodes (and relationships) in the knowledge graph. If you want to write a procedure that starts at a specific node, then you don’t need to iterate the whole graph but can instead have parameters for specific nodes or relationships on the procedure method, such as
pub fn get_relationship_types(node: &Node) -> Stream<RelationshipTypes> {...}.
Back in Example 5-7 you read in data file from a web- or filesystem-hosted JSON file and enriched the knowledge graph. That works fine for simple JSON retrieval services, but most APIs are more complicated. However, using the same pattern from Example 5-13, you can write a custom procedure that accesses service APIs too. Remember that a custom procedure can be any code you like, provided it conforms to the procedure interface.
Data Fabric with Specialized Data Virtualization Platforms
Section titled “Data Fabric with Specialized Data Virtualization Platforms”Specialized platforms like Dremio, Denodo, Data Virtuality, and others provide the capabilities to deploy broader data fabrics built on data virtualization. Such solutions support connectors for multiple data sources, advanced query delegation, caching, and a GUI for designing logical views. When deployed alongside such specialized data fabric technology, the knowledge graph will act as one master source of data being integrated in the fabric for golden record, deduplication, and so forth.
Complementary Tools and Techniques
Section titled “Complementary Tools and Techniques”While the drivers, functions, and procedures are popular ways of connecting to a knowledge graph, other integration tools might be used, depending on the surrounding systems. For example, you might have to provide an API to the knowledge graph so that it can be consumed from a wide range of user-facing applications. Or you might need to run ETL tasks to take data from upstream systems and use it to enrich the knowledge graph. You may want to move data between the knowledge graph and your analytics systems or have real-time data streamed into or out of the knowledge graph. Fortunately, there is a rich set of tools available for each of these requirements. The following sections provide an overview of them, so you can implement the right ones for your system with confidence.
GraphQL
Section titled “GraphQL”GraphQL is an API toolkit that originated from Facebook. Its original purpose was to provide an API to the underlying social graph stored in TAO (Facebook’s social graph service). Today, GraphQL is a framework for API construction (that defines types, schemas, messages, and so forth) and a runtime environment (GraphQL servers) for executing API calls. While it has “graph” in its name and is certainly useful for exposing knowledge graphs to consumers, it is a general-purpose toolkit that can be happily used for nongraph systems too. The basic system architecture is a simple client-server setup, as shown in Figure 5-7.
Figure 5-7. The high-level architecture of a GraphQL-based knowledge graph system
Using GraphQL to access a knowledge graph stored in a native graph database offers several advantages. These include a consistent graph data model and increased developer productivity, particularly when GraphQL is widely used across the enterprise.
Despite its name, GraphQL doesn’t come with any built-in affordances for using the topologies in knowledge graphs. However, in Neo4j’s GraphQL implementation, you can use the @relationship directive to describe relationships between nodes. For instance, based on the people and places examples in Chapter 4, you can create a GraphQL type system for an API that will allow users to query for who lives where. You can see this in Example 5-14.
Example 5-14. Using @relationship to create a GraphQL type system that includes links between records
type Place { city: String! country: String people: [Person!]! @relationship(type: "LIVES_IN", direction: IN)}
type Person { name: String! home: Place! @relationship(type: "LIVES_IN", direction: OUT)}Using @relationship in Example 5-14 has enriched an otherwise simple schema of documents with the ability to store data as knowledge graphs. Along with other data like city and country, a Place can have a non-null array of non-null Person records connected via LIVES_IN relationship records. Conversely, a Person has a name and a non-null LIVES_IN relationship to a Place.
Intuitively, you can see how Example 5-14 cleanly maps onto an underlying knowledge graph. But importantly, it provides strict guidance to the caller on the nature of the data that can be retrieved through the API.
To query or update the underlying graph, you can now send GraphQL from your GraphQL client to the server. In Example 5-15 you can see the GraphQL payload (query) sent from client to server.
Example 5-15. Updating a knowledge graph via GraphQL
mutation { createPlaces( input: { city: "Sydney" country: "Australia" people: { create: [ { node: { name: "Skippy" } } { node: { name: "Cate Blanchet" } } ] } } ) { places { city country people { name } } }}GraphQL returns the response shown in Example 5-16.
Example 5-16. Response from a knowledge graph update via GraphQL
{ "data": { "createPlaces": { "places": [ { "city": "Sydney", "country": "Australia", "people": [ { "name": "Skippy" }, { "name": "Cate Blanchet" } ] } ] } }}As an API description/construction framework, GraphQL works very well with knowledge graphs, particularly where the knowledge graphs sit near the user in a system architecture. For an in-depth book on integrating knowledge graphs with GraphQL, see Full Stack GraphQL Applications With React, Node.js, and Neo4j (https://oreil.ly/-7Wo9) by William Lyon (Manning).
Kafka Connect Plug-In
Section titled “Kafka Connect Plug-In”Apache Kafka is a popular enterprise middleware platform, acting as the glue between systems. At its simplest, it is a reliable publish/subscribe system for moving messages between systems at high volume. At its most sophisticated, it is itself a database and query engine for processing records as they flow through the business.
Integrating knowledge graphs with Kafka is straightforward. Using Kafka Connect Neo4j Connector (https://oreil.ly/qz76o), your knowledge graph can serve as a source of data, such as change data (or change data capture), or as a sink to ingest data from Kafka events into your knowledge graph.
At a systems level, the architecture is straightforward. Figure 5-8 shows how a query is executed periodically over the knowledge graph to publish data from your knowledge graph into Kafka for consumption by downstream systems.
Figure 5-8. Periodically executing a Cypher query over a knowledge graph to publish data to Kafka
Configuring the Neo4j Streams plug-in to publish updates from a knowledge graph is also straightforward. In Example 5-17 a knowledge graph is set up to publish the details of any new arrivals to Berlin once every 5 seconds (5,000 ms as it is written in the configuration). Correspondingly, in the model you must change the original since property on LIVES_IN relationships from Chapter 3 to a more granular timestamp that meets both the needs of the model and the publishing mechanism. Then the Cypher query will be run periodically to find the patterns like (Person)-[:LIVES_IN {since:'2015-06-24T12:50:35.556+0100'}]->(:Place {city:'Berlin'}) from which you can easily return the person’s name and the timestamp when they moved. The full query is shown along with the other necessary configuration in Example 5-17.
Example 5-17. Configuration for a query to periodically execute over a knowledge graph, publishing results to Kafka
{ "name": "Neo4jSourceConnectorAVRO", "config": { "topic": "new-arrivals-in-Berlin", "neo4j.streaming.poll.interval.msecs": 5000, "neo4j.streaming.property": "timestamp", "neo4j.streaming.from": "NOW", "neo4j.enforce.schema": true, "neo4j.source.query": "MATCH (p:Person)-[li:LIVES_IN]->(:Place {city:'Berlin', country:'DE'}) WHERE li.timestamp > $lastCheck RETURN p.name AS name, li.timestamp AS since" }}Both architecturally and practically, it’s just as straightforward to ingest data into your knowledge graph from Kafka. Figure 5-9 shows the general approach.
Figure 5-9. Receiving messages from Kafka and using Cypher MERGE to insert data into the knowledge graph
At a more detailed level, you use Cypher to unpack Kafka messages into the knowledge graph. In Example 5-18 you can see an example of the kind of patterns into which data from Kafka messages can be decomposed. You subscribe to a particular topic (e.g., new-arrivals-in-Berlin), which gives you access to data in messages published to it. You access data in the messages through the event variable and use that data to enrich your knowledge graph using Cypher features like MERGE.
Example 5-18. Configuration to ingest data from a Kafka topic into your knowledge graph
{ "name": "Neo4jSinkConnector", "config": { "topics": "new-arrivals-in-Berlin", "neo4j.topic.cypher.new-arrivals-in-Berlin": "MERGE (person:Person {name: event.name}) MERGE (place:Place {city: event.city, country: event.country}) MERGE (person)-[LIVES_IN {since: '2021-06-12T10:31:11.553+0100'}]->(place)" }}There are of course other operational details, such as how to set up Kafka and install the Streams plug-in into Neo4j, which you will need to solve to use this technique. The Neo4j Kafka documentation (https://oreil.ly/u8GvG) can help.
Neo4j Spark Connector
Section titled “Neo4j Spark Connector”Apache Spark is a (distributed) data processing framework for working with large data sets. It’s a common enterprise tool that integrates well with databases and filesystems as data sources and sinks for (parallel) processing. Its developer-friendly API allows for complex data-processing operations to express succinctly as a sequence of stages whose execution can be farmed out to a compute cluster without requiring specialist distributed processing skills.
Unsurprisingly, there are connectors (https://oreil.ly/ggESU) that allow Spark to treat your knowledge graph as both a source and a sink for data. Using the connectors, Spark developers are able to read in data from a knowledge graph for use in their processing pipelines as well as write back to the knowledge graph any results from those computations.
Installing (https://oreil.ly/oh_7J) the Neo4j Connector for Apache Spark connector is simply a matter of copying the appropriate .jar file into your Spark environment. Once the connector is installed, you can perform operations on the underlying graph. The simplest operations are reading and writing to the graph by label and predicate, as shown in Example 5-19. Leaving out the predicate where statement is fine too, but more data will be exchanged between Spark and Neo4j.
Example 5-19. Reading into Spark from Neo4j by label and predicate
import org.apache.spark.sql.{SaveMode, SparkSession}
val spark = SparkSession.builder().getOrCreate()
val df = spark.read.format("org.neo4j.spark.DataSource") .option("url", "bolt://localhost:7687") .option("authentication.basic.username", "neo4j") .option("authentication.basic.password", "neo4j") .option("labels", ":Person") .load()
df.where("name = 'John Doe'").where("age = 32").show()It’s also possible for Spark to perform a Cypher read query over your knowledge graph. You can see this in Example 5-20 where one option is a query whose value is the Cypher query to be executed. Note that it is good practice to return just data values from the query rather than full nodes and relationships to minimize the work involved in data transfer.
Example 5-20. Reading into Spark from Neo4j by Cypher query
import org.apache.spark.sql.{SaveMode, SparkSession}
val spark = SparkSession.builder().getOrCreate()
spark.read.format("org.neo4j.spark.DataSource") .option("url", "bolt://localhost:7687") .option("query", "MATCH (n:Person)-[FOLLOWS]->(:Person {name:'emileifrem'}) WITH n LIMIT 20 RETURN id(n) AS id, n.name AS name") .load() .show()For writes there is a similar idiom. You can insert nodes by label into the knowledge graph, as shown in Example 5-21.
Example 5-21. Writing from Spark into Neo4j by node label
import org.apache.spark.sql.{SaveMode, SparkSession}import scala.util.Random
val spark = SparkSession.builder().getOrCreate()import spark.implicits._
case class Person(name: String, surname: String, age: Int)
val ds = ( // Populate the data source here).toDS()
ds.write .format("org.neo4j.spark.DataSource") .mode(SaveMode.ErrorIfExists) .option("url", "bolt://localhost:7687") .option("labels", ":Person") .save()You can insert into Neo4j using Cypher’s patterns too, of course, which is shown in Example 5-22.
Example 5-22. Writing from Spark into Neo4j by Cypher query
import org.apache.spark.sql.{SaveMode, SparkSession}
val spark = SparkSession.builder().getOrCreate()
// Populate data frame in Sparkval df = // ...
// Save contents to knowledge graphdf.write .format("org.neo4j.spark.DataSource") .option("url", "bolt://second.host.com:7687") .option("relationship", "FOLLOWS") .option("relationship.source.labels", ":Person") .option("relationship.source.save.mode", "Overwrite") .option("relationship.source.node.keys", "source.name:name") .option("relationship.target.labels", ":Person") .option("relationship.target.save.mode", "Overwrite") .option("relationship.target.node.keys", "target.name:name") .save()In turn, Example 5-22 maps to Cypher, as shown in Example 5-23.
Example 5-23. Cypher code produced and executed on Neo4j as a result of a write from Spark
UNWIND $events AS eventMERGE (source:Person {name: event.source.name})SET source = event.sourceMERGE (target:Product {name: event.target.name})SET target = event.targetCREATE (source)-[rel:FOLLOWS]->(target)SET rel += event.relWhen writing into your knowledge graph from Spark, you must also provide some guidance on whether writes should use Cypher’s
CREATE, which allows duplicate patterns, orMERGE, which does not. In your code, settingSaveMode.ErrorIfExistswill build aCREATEquery, whereasSaveMode.Overwritebuilds aMERGEquery.
While Spark is powerful, its data model is quite different from that of a knowledge graph. When you choose to use Spark to analyze or enrich your knowledge graph, you’ll have to manage the mapping between its tabular model and your knowledge graph. Think of the Spark connector as plumbing that enables the user to specify transformations between the two worlds, much like a traditional ETL tool, albeit at a lower, textual level of abstraction.
Apache Hop for ETL
Section titled “Apache Hop for ETL”If the Spark connector in “Neo4j Spark Connector” can be thought of as a special-purpose ETL tool, then you should also be aware of general-purpose ETL tools in the context of knowledge graphs. Modern ETL tools come in a variety of configurations, from utilities you install on your computer to cloud-hosted services. In any case, the value of an ETL tool is that it enables connectivity with a wide variety of systems (not limited to knowledge graphs or even databases) and functionality to allow you to map data elements between systems conveniently.
As authors, we are agnostic about which ETL tool you choose. In this section, Apache Hop has been chosen because it’s open source and has good connectivity for knowledge graphs hosted in Neo4j. Our recommendation would be to use the ETL tool that has been chosen for your enterprise. In the absence of an enterprise standard, then open source or cloud tools (e.g., AWS Glue, Cloud ETL, etc.) are reasonable choices.
Most ETL tools provide low-code/no-code environments to help you to orchestrate data flows to and from your knowledge graphs (and other systems). For example, in Figure 5-10 you can see how the ETL tool has been configured to:
- Check for system availability
- Set up the knowledge graph indexes and constraints
- Cleanse import data from Wikipedia
- Run an import job into the knowledge graph
Figure 5-10. An Apache Hop ETL workflow for loading Belgian beer data into a knowledge graph (image based on Apache Hop documentation)
Within the workflow, you configure mappings from source data systems onto your knowledge graph (or vice versa). Again, this is typically low-code/no-code, as shown in Figure 5-11.
Figure 5-11. An Apache Hop mapping from Wikipedia data into a Neo4j knowledge graph (image based on Apache Hop documentation)
The mappings in Figure 5-11 are quite intuitive, if you understand brewing! Brands, breweries, and so on become nodes in the knowledge graph while the percentage label becomes a relationship between strength and evaluation nodes. While you do require some domain knowledge for this task (and we authors feel sampling Belgian beers would be a fun project to learn), you don’t require much technical knowledge. It’s a matter of point and click.
For more sophisticated mappings, you can also specify Cypher queries to run for knowledge graph ingress and egress. In this case, you provide parameterized Cypher to Hop and then use the UI tool to map data onto those parameters. At runtime, Hop binds values to those parameters and runs the Cypher queries to load data into or retrieve data from the knowledge graph. Finally, once the workflow has finished, the result is a knowledge graph about Belgian beers—both useful and delicious!
Integrating an Embedded Rust Graph Database (petgraph + redb)
Section titled “Integrating an Embedded Rust Graph Database (petgraph + redb)”If you have chosen the embedded architecture outlined in Chapters 3 and 4 using petgraph and redb, integrating your knowledge graph with other information systems requires a different approach than using a network driver like neo4rs.
Because your knowledge graph lives entirely within the memory space of your application, you act as the server. To integrate with a broader data fabric, you must expose your embedded graph to the outside world, typically by wrapping it in a web framework like axum or actix-web.
This architectural pattern is incredibly powerful for microservices. Your service owns the graph data locally, achieving microsecond query latencies, while exposing a clean REST or GraphQL API to other systems in the enterprise.
Figure 5-12. Wrapping an embedded petgraph + redb database in an Axum web service.
To implement this, you can define an axum server that holds an Arc<RwLock<Graph>> (for safe concurrent reads and exclusive writes) and an Arc<Database> (for persistence). Example 5-24 demonstrates how to expose a REST endpoint that queries the graph.
Example 5-24. Exposing a petgraph knowledge graph via a REST API using Axum
use axum::{ extract::{Path, State}, routing::get, Json, Router,};use petgraph::graph::{Graph, NodeIndex};use serde::{Deserialize, Serialize};use std::sync::Arc;use tokio::sync::RwLock;use redb::Database;
// Define the graph schema#[derive(Serialize, Deserialize, Debug, Clone)]pub enum NodeData { Person { name: String }, Place { city: String },}
#[derive(Serialize, Deserialize, Debug, Clone)]pub enum EdgeData { LivesIn, Friend,}
// Our application state shared across HTTP handlersstruct AppState { graph: Arc<RwLock<Graph<NodeData, EdgeData>>>, db: Arc<Database>, // For writing updates back to disk}
// A simple response struct#[derive(Serialize)]struct ResidentResponse { city: String, residents: Vec<String>,}
// The HTTP handler: GET /city/:city_name/residentsasync fn get_residents( Path(city_name): Path<String>, State(state): State<Arc<AppState>>,) -> Json<ResidentResponse> { let graph = state.graph.read().await; let mut residents = Vec::new();
// 1. Find the target city node let city_node_idx = graph.node_indices().find(|&i| { if let NodeData::Place { city } = &graph[i] { city == &city_name } else { false } });
// 2. Traverse incoming LIVES_IN edges if let Some(idx) = city_node_idx { let mut incoming = graph.neighbors_directed(idx, petgraph::Direction::Incoming); while let Some(neighbor_idx) = incoming.next() { if let NodeData::Person { name } = &graph[neighbor_idx] { residents.push(name.clone()); } } }
Json(ResidentResponse { city: city_name, residents, })}
#[tokio::main]async fn main() { // Initialize embedded database and graph let db = Arc::new(Database::create("embedded_graph.redb").unwrap()); let graph = Arc::new(RwLock::new(Graph::<NodeData, EdgeData>::new()));
// (Load data from redb into petgraph here, as shown in Chapter 3)
let state = Arc::new(AppState { graph, db });
// Build our Axum router let app = Router::new() .route("/city/:city_name/residents", get(get_residents)) .with_state(state);
// Run the web server let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); println!("Embedded Graph API running on http://localhost:3000"); axum::serve(listener, app).await.unwrap();}By wrapping your petgraph + redb stack in an API, you maintain the extreme performance benefits of an embedded Rust database while seamlessly integrating into the modern enterprise data fabric. You can easily extend this pattern to support async-graphql for rich GraphQL queries, or hook into a Kafka client crate like rdkafka to stream updates out of your embedded graph in real time.
Summary
Section titled “Summary”At this point on your journey into knowledge graphs, you’ve tackled some significant technical topics on graph database fundamentals, data loading, and data fabric. It takes real effort to understand these tools and how they overlap, so congratulations on getting this far!
From here on, you are going to continue your journey out of the tools and up the stack towards the user. In Chapter 6, you’ll take your first steps into graph algorithms to process knowledge graphs to gain actionable insight.