jsonredisioredis

How to store object of arrays in redis?


I have a json object structure like

{
  R10: [{ancestors: ['121', '122', '123']}, {ancestors: ['221', '222', '223']}, ...],
  R11: [{ancestors: ['1121', '1122', '1123']}, {ancestors: ['1221', '1222', '1223']}, ...],
  R12: [{ancestors: ['2121', '2122', '2123']}, {ancestors: ['2221', '2222', '2223']}, ...],
  .
  .
}

how to store it in redis for easy accesible. if i want to get ancestors of R10 and R11?

Thanks in advance!


Solution

  • Redis has 2 modules that are included in the redis-stack package,

    1. RedisJSON will let you store the JSON objects as JSONs, and perform JSON operations on them.
    2. RediSearch will give you even more capabilities for querying your data and supports indexing JSONs.

    You can get a Redis-stack image from DockerHub, or follow the instructions from the documentation here.

    Here is a short example using the redis CLI

    127.0.0.1:6379> JSON.SET R10 $ '[{"ancestors": ["121", "122", "123"]}, {"ancestors": ["221", "222", "223"]}]'
    OK
    127.0.0.1:6379> JSON.SET R11 $ '[{"ancestors": ["1121", "1122", "1123"]}, {"ancestors": ["1221", "1222", "1223"]}]'
    OK
    127.0.0.1:6379> JSON.SET R12 $ '[{"ancestors": ["2121", "2122", "2123"]}, {"ancestors": ["2221", "2222", "2223"]}]'
    OK
    

    And then

    127.0.0.1:6379> JSON.GET R10 $.[0].ancestors
    "[[\"121\",\"122\",\"123\"]]"
    
    127.0.0.1:6379> JSON.GET R10 $.[*].ancestors
    "[[\"121\",\"122\",\"123\"],[\"221\",\"222\",\"223\"]]"
    
    127.0.0.1:6379> JSON.GET R10 $.[*].ancestors[*]
    "[\"121\",\"122\",\"123\",\"221\",\"222\",\"223\"]"