fancy
fancy

Reputation: 51463

Working with nested objects in Redis?

Say I have a hash where a nested property could change.

"key1": {
  "prop1": {
    "subprop1": "could_change"
  }
}

If I get sent the info that prop1.subprop1 has changed can I preform atomic updates on this property? Right now node_redis saves prop1 as a string that says '[object Object]'. If I JSON.stringify() the obj then I would need to retrieve the object, parse to object in memory, make the edit, and then stringify and save the object -- not knowing if something has changed in the mean time.

If I should be working with this data in a different way could someone please explain? I have an object with may nested attributes that I need to be able to update parts of, in addition to needing to retrieve as a whole object.

Thanks for any help!

Upvotes: 4

Views: 1554

Answers (1)

Fritzy
Fritzy

Reputation: 1014

Lua scripting or a lock pattern would solve your problem.

EVAL 'local obj = cjson.decode(redis.call("GET", "key1")); obj.prop1.subprop1 = ARGV[1]; redis.call("SET", "key1", cjson.encode(obj));' 0 "did_change"

You could even make something more advanced in Lua for editing any key's JSON subobjects if you wanted to.

Look at the Redis SETNX command docs for an example of how to use a lock.

Upvotes: 6

Related Questions