NoSQL – How to Query Multiple Data in Schema Design

database-designnosqlredis

I just got a requirement, to build a web only with Redis.

Data of the web is something like this(I write as RDBMS):
User Info:
user_id,first_name,last_name,age,…..
Address:
address_id,city,state,country,….

There is no problem at all if only write one user or get one user with "user_id".

But, what should I do if want to get all user younger than 20, or all user live in New York?

I can save all user_id under a key 'New York', but that's ugly isn't it.
If want to add a new condition, that need scan all data to build the index.

And if the condition become, live in 'New York' and younger than 20, well….

Is there have some amazing way to do that with Redis?​

Best Answer

I can save all user_id under a key 'New York', but that's ugly isn't it.

No, it isn't ugly and it's very much what any RDBMS does when it maintains an index. The difference with Redis is that it doesn't do that for you so you'll have to do these keys' management in the code.

But, what should I do if want to get all user younger than 20, or all user live in New York?

Consider using Redis' Sets and Sorted Sets for storing these attributes. Redis provides several set operations (union, intersect...) that make building these conditions easier.

Is there have some amazing way to do that with Redis?​

That's pretty much it. It's always about a trade off - choose a full-fledged RDBMS for the comfort and you'll pay with performance, with Redis it's the other way around :) That said, it's not that bad once you "repress" some of your currently-dominant relational database instincts.

Another viable approach that may fit your requirements is to use an object mapper to abstract some of the underlying Redis details. Depending on your choice of programming language, there are quite a few out that do a lot of the work for you (at the expense of a little performance of course ;)).