Graph Cache: Caching Data in N-Dimensional Structures
In this tutorial, we will walk you through the usage of the basic APIs provided in the Java Graph Cache library.
Join the DZone community and get the full member experience.Join For Free
As is already well established, Graph Databases such as Neo4J are great for intuitively storing relationship data in graph-like structures. Neo4J has been around since 2007 and in its current iteration, it is an extremely robust and versatile NoSQL database framework. But there are limitations to graph databases, namely:
- Query optimization options are limited although this challenge is certainly being addressed in newer versions.
- Data partitioning is a tough proposition so horizontal scaling becomes challenging.
- Computationally intensive or costly queries — Most real-world graphs are highly dynamic and often generate large volumes of data at a very rapid rate. One challenge here is how to store the historical trace compactly while still enabling efficient execution of point queries and global or neighborhood-centric analysis tasks.
- Queries spanning multiple hierarchies can be time-consuming and not suitable for real-time querying.
- Design is only as good as the implementation and this is where the human element comes in. Not everyone can think in terms of graphs.
But the Graph Cache implementation does not seek to address only the shortcomings of Graph Databases. Over and above these things, Graph Cache seeks to provide a performant framework to
1. Store any data in a relationship form so that how the data is related also takes on meaning in the form of metadata on edges that connect the data
2. Eliminate data redundancies — Since Data is stored in parent-child form, a lot of redundancies in data are avoided by moving repeated values to a parent node. For eg, A Jaguar can be a Car as well as an animal. Storing Jaguar in a regular cache would mean
Item 1 -> Jaguar -> Car
Item 2 -> Jaguar -> Animal
You see that Jaguar object representation is repeated in the value against the keys Item 1 and Item 2.
But in a graph
As the Jaguar object becomes a parent with its own properties and metadata that are self-contained, it is stored only once as a parent, and all its relationships are maintained as Children, thus eliminating data redundancy.
On the scale, this can lead to tremendous savings on the amount of data stored.
2. Store minimal subgraphs of deep hierarchical relationships to ensure extremely fast retrieval of data at the leaves by avoiding traversal across the full depth of the tree. The shallower the subgraph that is stored in the cache, the faster the retrieval of data.
3. Represent data in 3 dimensions — Parent node, Edge, and Child node, each having metadata around the relationships so that driving insights from how the data is related becomes easier.
4. Primarily maintained in memory — To keep it truly performant, it is maintained in memory, close to the business logic to ensure fast computation.
5. Keeping it simple by providing abstractions over how the data is maintained in the graph. At the same time give fine-grained control of how you want it to be stored as well.
With some of these key benefits in mind, let's talk about the Java implementation.
The Java Interfaces have been built over the following APIs:
1. JGraphT — A Java library of graph theory data structures and algorithms
2. Caffeine — a high performance, near-optimal caching library
Looking at the POM file you will see the following dependencies listed:
JGraphT provides the backing Graph structure to store the data in graph format, specifically Multigraphs.
Caffeine provides a high performance in-memory Caching solution to specifically store minimal subgraphs.
Let's further deep dive into the available Objects and APIs.
The Node object itself is used to store:
1. Identifier: A unique identifier that can be used to search for it and retrieve the data stored in it.
2. Data: Any data that you need to store in the Node. Can be any Java type that inherits from Object class.
The DataWeighedEdge class represents the Edges that connect nodes and define the relationships between them. The provided fields are
1. RelationMetadata: This field can be used to store any metadata that provides further information into how the nodes that are connected by the edge are related. By default this field stores the identifiers of the parent and child node in a string format as
The DataWeighedEdge also provides the Source (Parent) node and Target (Child) node that the edge connects.
Backing Graph APIs
The GraphInstance class creates the MultiGraph instance of Nodes connected by DataWeighedEdge edges.
We have the GraphUtil class maintaining the instance of the individual GraphInstance created above that will be stored in the cache. Following methods are provided by GraphUtil:
void addRelationship(Node parentNode, Node childNode):
Add a Parent node, a child node, and an edge connecting the two into the GraphInstance.
List<Node> findNodes(String identifier):
Given an identifier that uniquely identifies a Node object, find the Node that has the identifier within the
DataWeighedEdge findEdge(String parentIdentifier, String childIdentifier):
Given the unique parent node identifier and child identifier, find the edge that connects the two nodes within the GraphInstance.
Get the GraphInstance stored in this instance of the Util.
The GraphUtil class is the utility class that provides easy to use APIs that allow developers to store data into Minimal Subgraphs. These subgraphs are the actual graph structures that are cached in the Caffeine cache.
The Cache itself is a Caffeine instance that as a best practice is maintained in memory close the business logic itself.
To initialize the instance The CacheInitializer class is used that provides a default api to initialize a Cache:
Cache defaultInitialize(Long maxRecords, Integer expireAfterWriteInMinutes,
Initialize the Caffeine cache instance with:
maxRecords: a maximum size defined by maxRecords that can be stored
expireAfterWriteInMinutes: defines the time unit in minutes before a record is marked as invalid in the cache since it was last written
expireAfterAccessInMinute: defines the time unit in minutes before a record is marked as invalid in the cache since it was last accessed
Caffeine createSelfCustomizableInstance(): Return an instance of a Caffeine builder object that can be customized according to the developers' own preferences.
Once the Cache instance is initialized, the CacheUtil class provides the utility APIs to store the Graph data into the Cache:
void initCacheDefault(Long maxRecords, Integer expireAfterWriteInMinutes,
Initializes the cache instance with default params and creates the cacheInstance that is maintained within the CacheUtil.
Clear all data from the cache
void removeKey(String key):
Remove the data pertaining to the key from the cacheInstance
void cacheGraph(String key, GraphInstance graph):
Cache an instance of the minimal subgraph Instance with any key that the developer provides
void cacheNode(String key, Node node):
Cache just a Node object with data and an identifier that identifies it
void cacheEdge(String key, DataWeighedEdge edge):
Cache a DataWeighedEdge object containing a Source vertex, a child vertex, and the metadata that defines the relationship.
Get the cached Graph, Node, or DataWeighedEdge object that pertains to the key.
The CacheUtil class intentionally provides APIs to cache Nodes and Edges as well to give flexibility to developers in using the Cache just like any other Keystore as well.
So What Can the GraphCache Be Used for?
The answer is Caching anything like a relationship. It could be:
1. The state of a Parent div that contains a child div in a React app. The Edge represents the route between the two.
2. Stock prices across days for a stock listed in multiple stock exchanges and priced in different currencies.
3. Service mesh analytical data on the health information of all the connected nodes and how each node depends on each other.
We can store a subgraph in this way. Retrieval can be done using the graphKey:
graphInst = (GraphInstance)cacheUtil.getObject(graphKey);
In a similar fashion, we can cache Nodes as well as Edges themselves into the CacheUtil->CacheInstance.
Hopefully, you will find this primer on the Graph Cache useful for your application.
The code can be found on GitHub at the URL:
It is open-source, so feel free to raise a pull request if you feel like contributing to the project.
Opinions expressed by DZone contributors are their own.