Documentation

How to query Graph data in Redis using Ruby

Ajeet Raina
Author
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-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:

 docker run -p 6379:6379 --name redis/redis-stack
 info modules
 # Modules
 module:name=graph,ver=20405,api=1,filters=0,usedby=[],using=[],options=[]
 gem install redisgraph
 Fetching redisgraph-2.0.3.gem
 Successfully installed redisgraph-2.0.3
 1 gem installed

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

 bundle install

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)
 response.stats

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

 response = r.query(cmd)

 response.print_resultset
  ruby test.rb
 redis-cli
 127.0.0.1:6379> monitor
 OK
 1632716792.038955 [0 172.17.0.1:57804] "info"
 1632716792.041201 [0 172.17.0.1:57804] "GRAPH.QUERY" "sample" "CREATE (:person {name: 'Jim', age: 29})-[:works]->(:employer {name: 'Dunder Mifflin'})" "--compact"
 1632716792.042751 [0 172.17.0.1:57804] "GRAPH.QUERY" "sample" "MATCH ()-[:works]->(e:employer) RETURN e" "--compact"
 1632716792.044241 [0 172.17.0.1:57804] "GRAPH.QUERY" "sample" "CALL db.propertyKeys()"
 1632716812.060458 [0 172.17.0.1:57962] "COMMAND"
 1632716813.148710 [0 172.17.0.1:57962] "GRAPH.QUERY" "sample" "CREATE (:person {name: 'Jim', age: 29})-[:works]->(:employer {name: 'Dunder Mifflin'})" "--compact"
  • Learn more about RedisGraph in the Quickstart tutorial.