Will the LPUSH command work on a record that was initialized from JSON?

redis

Solution

No. Redis is format agnostic. It cannot parse JSON, and it is not a document oriented database.

LPUSH applies to Redis list objects only.

What can be done however using Lua Redis 2.6 server-side scripting capability, is a script to decode a JSON object, add the item, encode back the object and store it.

For instance, with the following JSON object:

set users:1 "{\"id\":1,\"name\":\"Rocco\",\"age\":50,girlfriends:[\"Ulla\"]}"

adding a new girlfriend can be implemented in one operation using an eval command:

eval "local t = cjson.decode( redis.call('get',KEYS[1] ))
  if t.girlfriends then
     table.insert(t.girlfriends,ARGV[1])
  else
     t.girlfriends = {ARGV[1]}
  end
  return redis.call('set',KEYS[1], cjson.encode(t))
" 1 user:1 Augusta

Another possibility is to avoid storing JSON objects directly in Redis, but write a layer to convert JSON objects into several Redis keys (isolating the lists sections in their specific keys).

For instance:

 { "id":1, "name": "Rocco", "age":50,
  girlfriends: [ "Ulla", "Bella", "Josepha", "Isabella" ] }

could be stored as:

 HMSET users:1:info name Rocco age 50
 RPUSH users:1:girlfriends Ulla Bella Josepha Isabella

The main benefits of this approach are performance and partial update support. Main drawback is some flexibility is lost and conversion code may be tedious to write.

Problem

If a redis record was set from a JSON object that contains a list in it, could the LPUSH command be later used on that list to update it? (using redis on node.js) Thanks

Original source