Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis storing and querying complex structures

I want to store a complex structure as JSON object in a Redis Sorted Set.

ZADD "mysetkey" 100 [ {"A":"100"}, {"B":"50"}, {"C":"180"}, {"D":"200"} ] 
ZADD "mysetkey" 101 [ {"A":"10"}, {"B":"50"}, {"C":"70"}, {"D":"200"} ] 
ZADD "mysetkey" 88 [ {"A":"300"}, {"B":"50"}, {"C":"110"}, {"D":"200"} ] 

Now is there an easy to perform operations or searches on the values stored ? For example, if I want to get sumof(A) for all elements ? Or get all elements that have value of A < 20 AND value of C > 100.

My understanding is that it's not possible because Redis stores everything as String. But wanted to confirm it anyway.

Also, it is possible to achieve this in Redis by using a combination of data structures supported by Redis.

like image 339
Soumya Simanta Avatar asked Oct 22 '22 07:10

Soumya Simanta


1 Answers

You can implement the functionality that you need in a Lua script. When evaluating Lua script Redis loads cjson library among others and this library allows you to parse your JSON to extract values from it. See the EVAL command. http://redis.io/commands/eval

A code sample from http://www.kyne.com.au/~mark/software/lua-cjson-manual.html:

json_text = '[ true, { "foo": "bar" } ]'
value = cjson.decode(json_text)
-- Returns: { true, { foo = "bar" } }

Mind that Redis evaluates scripts one at a time, and no other clients can run their commands while a script is running, so this might now be suitable for you.

like image 143
akonsu Avatar answered Oct 29 '22 13:10

akonsu