Reputation: 1792
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
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:
user:1:posts
(or something similar) which contains either the full keys (user:1:post:1
, etc) or the relative keys (1
, etc)user:1:posts
(or something similar) which contains the posts keyed by their idI'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:
1
with value {"PostId":"1","Content":"Test content"}
2
with value {"PostId":"2","Content":"Test content"}
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