user2988129
user2988129

Reputation: 301

redis json sql style query

I have a bunch of json that I would like to store in Redis

{
    "foo": "37",
    "bar": "Alex",
    "baz": "Tom",
    "type": "test",
    "date": "12/12/2012 12:12:12
}

but coming from an sql background, I'm not too sure what the best way to go about doing:

SELECT * FROM table WHERE "foo" = "37" AND "baz" = "test" ORDER BY date DESC

I've looked at hashes, but I'm unclear if Redis able to perform queries as the one above?

Upvotes: 1

Views: 794

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 50022

The way to go about this with Redis is to build indices. For example, consider the following flow to "insert" your data into a hash key and build the proper indices:

HMSET somekeyname foo "37" bar "Alex" baz "Tom" type "test" date "12/12/2012 12:12:12"
SADD foo_index:37 somekeyname
SADD baz_index:test somekeyname

This will create a key called somekeyname of type HASH with the relevant data in it. Additionally, it will create/update two sets that we'll use as indices. Now, to get the keys that match your SQL select statement, do something like:

SINTER foo_index:37 baz_index:test

This will return to you any key names that fulfill the conditions. Sorting the results can be done at the client side or by replacing SINTER with SINTERSTORE and using Redis' SORT command on the destination key.

Upvotes: 1

Related Questions