Redis is very performant, due to performance consideration, sometimes we need to use Redis as a database, when querying a redis database, we need to consider indexing and filtering.
We can use SortedSet as Index.
For example, for a table of schema (id int, name text, age int, ...), we could save each row in a Hash, keyed by id, and save (age, id) pairs in SortedSet.
For a query like "select * from table order by age limit OFFSET, LIMIT", first we use zrange to get ids from SortedSet, then do some *hmget*s to fetch the whole row.
But if we need to do where with order, things got complicated.
An easy way to do it is to use "compound indexes", we save ((field1, field2), id) instead of (field, id), make sure that (field1, field2) is fully ordered in the common sense.
This is fine when you only do it a few times for a few queries, but it's not ok for queries that may filter on several fields and order by several fields, too. In this case, number of compound indexes will soon be too large to manage.
If compound index is not available, what do database do to a query like "select * from table where score>=90 order by age limit OFFSET, LIMIT"?
Well, a straight forward method would be like below:
- load ranking 1-100 from "index" age
- see if these rows meet the where criteria
- if so, append it to a temporary index
- else, skip it
- if temporary index contains more than OFFSET+LIMIT elements,
- we then slice the temporary index and return
- otherwise, go to step 1, increase the ranking numbers we load.
The only problem for this algorithm is we need to do client-server communication hundreds or thousands of times to do a simple query.
Luckily, redis 2.6+ has lua built in, so it's possible to write lua scripting calculating in the server side(redis side), and return results like a real db.
This gist is an attempt to illustrate the possible combound index implementation in lua scripting.
Just want to mention that you misspelled "Redis" in your title :^)