How to cache JSON data in Redis with Ruby

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 RedisJSON docker container#

docker run -d -p 6379:6379 redislabs/redismod: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 = # Get a redis client
# Get/Set/Delete keys
obj = {
'id': "42",
'name': "Paul John",
'email': "",
'address': {
'city': 'London'
rcl.json_set("employee", Rejson::Path.root_path, obj)
rcl.json_set("employee",".id"), 43)
rcl.json_get "employee", Rejson::Path.root_path
rcl.json_del "employee", ""

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:> monitor
1627619198.040000 [0] "JSON.SET" "employee" "." "{\"id\":\"42\",\"name\":\"Paul John\",\"email\":\"\",\"address\":{\"city\":\"London\"}}"
1627619198.040876 [0] "JSON.SET" "employee" ".id" "43"
1627619198.042132 [0] "JSON.GET" "employee" "."
1627619198.042741 [0] "JSON.DEL" "employee" ""