How to query Graph data in Redis using Ruby

Ajeet Raina
Ajeet Raina, Former Developer Growth Manager at Redis

RedisGraph is the first queryable Property Graph database to use sparse matrices to represent the adjacency matrix in graphs and linear algebra to query the graph. Few of the notable features of RedisGraph includes:

  • Based on the Property Graph Model
  • Nodes (vertices) and Relationships (edges) that may have attributes
  • Nodes that can be labeled
  • Relationships have a relationship type
  • Graphs represented as sparse adjacency matrices
  • Cypher as query language
  • Cypher queries translated into linear algebra expressions

RedisGraph is based on a unique approach and architecture that translates Cypher queries to matrix operations executed over a GraphBLAS engine. This new design allows use cases like social graph operation, fraud detection, and real-time recommendation to be executed 10x – 600x faster than any other graph database.

RedisGraph Ruby Client#

redisgraph-rb is a Ruby gem client for the RedisGraph module. It relies on redis-rb for Redis connection management and provides support for graph QUERY, EXPLAIN, and DELETE commands.

Follow the steps below to get started with RedisGraph with Ruby:

Step 1. Run Redis Stack Docker container#

 docker run -p 6379:6379 --name redis/redis-stack

Step 2. Verify if RedisGraph module is loaded#

 info modules
 # Modules

Step 3. Loading the RedisGraph Ruby Module#

 gem install redisgraph
 Fetching redisgraph-2.0.3.gem
 Successfully installed redisgraph-2.0.3
 1 gem installed

Step 4. Install the prerequisites#

To ensure prerequisites are installed, run the following: bundle install

 bundle install

Step 5. Write a Ruby code#

Copy the below sample code and save it in a file "test.rb"

 require 'redisgraph'

 graphname = "sample"

 r = RedisGraph.new(graphname)

 cmd = """CREATE (:person {name: 'Jim', age: 29})-[:works]->(:employer {name: 'Dunder Mifflin'})"""
 response = r.query(cmd)

 cmd = """MATCH ()-[:works]->(e:employer) RETURN e"""

 response = r.query(cmd)


Step 6. Execute the Ruby code#

  ruby test.rb

Step 7. Monitor the Graph query#

 redis-cli> monitor
 1632716792.038955 [0] "info"
 1632716792.041201 [0] "GRAPH.QUERY" "sample" "CREATE (:person {name: 'Jim', age: 29})-[:works]->(:employer {name: 'Dunder Mifflin'})" "--compact"
 1632716792.042751 [0] "GRAPH.QUERY" "sample" "MATCH ()-[:works]->(e:employer) RETURN e" "--compact"
 1632716792.044241 [0] "GRAPH.QUERY" "sample" "CALL db.propertyKeys()"
 1632716812.060458 [0] "COMMAND"
 1632716813.148710 [0] "GRAPH.QUERY" "sample" "CREATE (:person {name: 'Jim', age: 29})-[:works]->(:employer {name: 'Dunder Mifflin'})" "--compact"


  • Learn more about RedisGraph in the Quickstart tutorial.