How would you efficiently store JSON in Redis?

Technology CommunityCategory: RedisHow would you efficiently store JSON in Redis?
VietMX Staff asked 3 years ago

There are many ways to store an array of Objects in Redis: 1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate):

INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}

Use when:

  • If you use most of the fields on most of your accesses.
  • If there is variance on possible keys
  1. Store each Object’s properties in a Redis hash:
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}

Use when:

  • If you use just single fields on most of your accesses.
  • If you always know which fields are available
  • If there are a lot of fields in the Object
  • Your Objects are not nested with other Objects
  • You tend to only access a small subset of fields at a time
  1. Store each Object as a JSON string in a Redis hash:
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'

Use when:

  • really care about not polluting the main key namespace
  1. Store each property of each Object in a dedicated key:
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}

Use when:

  • almost never preferred unless the property of the Object needs to have specific TTL or something

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. Option 1 (generally speaking) may be most preferable because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don’t want there to be a lot of keys in your database and you don’t care about things like TTL, key sharding, or whatever).

Also as a rule of the thumb, go for the option which requires fewer queries on most of your use cases.