Skip to main content

How to cache JSON data in Redis with Ruby


Profile picture for Ajeet Raina
Author:
Ajeet Raina, Former Developer Growth Manager at Redis

rejson-rb is a package that allows storing, updating and querying objects as JSON documents in a Redis database that is extended with the RedisJSON module. The package extends redis-rb's interface with RedisJSON's API, and performs on-the-fly serialization/deserialization of objects to/from JSON.

Step 1. Run Redis Stack docker container

 docker run -d -p 6379:6379 redis/redis-stack:latest

Step 2. Install Ruby

 brew install ruby

Step 3. Install RedisJSON Gem

 gem install rejson-rb

Step 4. Create a ruby file

Copy the below content and paste it in a file called 'employee.rb'.

 require 'rejson'

rcl = Redis.new # Get a redis client

# Get/Set/Delete keys
obj = {
'id': "42",
'name': "Paul John",
'email': "paul.john@gmail.com",
'address': {
'city': 'London'
}
}

rcl.json_set("employee", Rejson::Path.root_path, obj)

rcl.json_set("employee", Rejson::Path.new(".id"), 43)

rcl.json_get "employee", Rejson::Path.root_path

rcl.json_del "employee", ".address.city"

The above script uses RedisJSON commands to set the objects, alter the id to 43 and then perform the delete operation using 'json_del'

Step 5. Execute the script

 ruby employee.rb

You can verify what's happening in the background by running the monitor command in Redis CLI shell:

 127.0.0.1:6379> monitor
OK
1627619198.040000 [0 172.17.0.1:57550] "JSON.SET" "employee" "." "{\"id\":\"42\",\"name\":\"Paul John\",\"email\":\"paul.john@gmail.com\",\"address\":{\"city\":\"London\"}}"
1627619198.040876 [0 172.17.0.1:57550] "JSON.SET" "employee" ".id" "43"
1627619198.042132 [0 172.17.0.1:57550] "JSON.GET" "employee" "."
1627619198.042741 [0 172.17.0.1:57550] "JSON.DEL" "employee" ".address.city"

References