1

I am new to Redis, so excuse the question.

I am trying to make a list of hashes. For example (in JSON):

{
  userList: [ 
    { id: 1, name: 'Foo', ranking: 10 },
    { id: 2, name: 'Bar', ranking: 5 }
  ]
}

And then I want to:

  • Retrieve all the hashes (users) that have a ranking less than 10.
  • Delete all the hashes who have ranking 0.

How do you implement the last schema in Redis? Is it possible?

How do you filter the elements, and remove some of them?

Quarktum
  • 669
  • 1
  • 8
  • 26
  • Why redis? Use a real database. – Sergio Tulentsev Oct 09 '15 at 19:54
  • If you insist on redis, you'll have to maintain secondary indexes yourself (something that databases do _for_ you). Read about sorted set methods: http://redis.io/commands#sorted_set – Sergio Tulentsev Oct 09 '15 at 19:55
  • First of all, redis is a real database with different purposes than whatever you are referring to. I want to use redis because it adapts to my needs in this case, if you are interested in this read [this](http://stackoverflow.com/questions/19477821/redis-cache-vs-using-memory-directly). Also I have already read what you mentioned, but it doesn't answer the question. – Quarktum Oct 09 '15 at 20:03
  • 1
    You don't see how sorted sets help you implement this? You store rankings there, mapped to ids of your hashes. When you need to find hashes by rankings, you query sorted sets. When you add/delete a hash, you have to not forget to update sorted sets. This is called "secondary indexes" and it's a no-brainer in any database. – Sergio Tulentsev Oct 09 '15 at 20:08

1 Answers1

2

How do you implement the last schema in Redis? Is it possible?

Redis is schema-less. Let's call what you need a data storage approach.

One possible approach is using HSET or HMSET to add these JSON objects by id, where their id is the key and the JSON text is the value. We'll call this hash as users:byid.

This is the first part of the problem. Now you can get objects by id.

Now the next issue is you want to retrieve objects in a range of what you call ranking. In order to get this, you need to store your objects in a sorted set using ZADD. Sorted sets are sorted by score, and items are stored with a score. It sounds perfect for your use case!

Actually you're going to store the object ids in the whole sorted set:

zadd users:byranking 10 1 5 2

... where 10 is the score (i.e. your actual ranking value) and 1 the id and so on.

So, how you filter items by ranking? Using ZRANGEBYSCORE:

  • By ranking between 0 and 10, excluding 10. zrangebyscore users:byranking 0 (10
  • By ranking between 0 and 10, including 10. zrangebyscore users:byranking 0 10

The so-called ZRANGEBYSCORE will give you the ids of retrieved users. How you get their JSON text? Using HMGET:

 HMGET users:byid 1 2

...which will get both user with id 1 and 2, if 10 ranking is inclusive.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206