Amir Movahedi
Amir Movahedi

Reputation: 1792

Edit json object by lua script in redis

I want edit my json object before back from the Redis server, In my Redis server I have 4 keys:

user:1 {"Id":"1","Name":"Gholzam","Posts":"[]"}
user:1:post:1 {"PostId":"1","Content":"Test content"}
user:1:post:2 {"PostId":"2","Content":"Test content"}
user:1:post:3 {"PostId":"3","Content":"Test content"}

I want to get this context by lua script,How ? :

{"Id":"1","Name":"Gholzam","Posts":"[{"PostId":"1","Content":"Test
content"},{"PostId":"1","Content":"Test
content"},{"PostId":"1","Content":"Test content"}]}

Upvotes: 1

Views: 1050

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062492

The choice of client here is largely irrelevant; the important thing to do is: figure out the data storage. You say you have 4 keys - but it is not obvious to me how we we know, given user:1, what the posts are. Common approaches there include:

  • have a set called user:1:posts (or something similar) which contains either the full keys (user:1:post:1, etc) or the relative keys (1, etc)
  • have a hash called user:1:posts (or something similar) which contains the posts keyed by their id

I'd be tempted to use the latter approach, as it is more direct - so I might have:

  • user:1, a string with contents {"Id":"1","Name":"Gholzam","Posts":"[]"}
  • user:1:posts, a hash with 3 pairs:
    • key 1 with value {"PostId":"1","Content":"Test content"}
    • key 2 with value {"PostId":"2","Content":"Test content"}
    • key 3 with value {"PostId":"3","Content":"Test content"}

Then you can use hgetall or hvals to get the posts easily.

The second part is how to manipulate json at the server. The good news here is that redis provides access to json tools inside lua via cjson.

I am an expert in neither cjson nor lua; however, frankly my advice is: don't do this. IMO, redis works best if you let it focus on what it is great at: storage and retrieval. You probably can bend it to your whim, but I would be very tempted to do any json manipulation outside of redis.

Upvotes: 2

Related Questions