Alternative data model to using sorted set in redis (for a Django/Python project)
<p>I have a web application where users post text messages for others to read (kind of like Twitter).</p>

<p>I need to save the 50 latest <code>message_id</code> and the poster's <code>user_id</code> pairs (for processing later). I use redis backend and realized I can save these 50 latest pairs in a sorted set: <code>user_id</code> as a value and <code>message_id</code> as a score. </p>

<p>Now since <code>user_id</code> can be repeated, I would need to set the <code>NX</code> flag to <code>true</code>. This, according to <a href="http://redis.io/commands/zadd" rel="nofollow">the docs</a>, ensures that new members are added to the sorted set instead of updating existing ones. This helps because if the same user posts messages multiple times, new entries will be added to the sorted set, instead of overwriting existing ones. That keeps the data sane.</p>

<p>Here's the problem: my application uses python, and the NX flag wasn't introduced in redis 2.8.4 (the version I'm using). </p>

<p>So what alternatives do I have for efficiently saving the 50 latest <code>message_id</code> and <code>user_id</code> pairs using redis? Please advise.</p>

<hr>

<p>Switching <code>message_id</code> and <code>user_id</code> in the sorted set as value and score doesn't work for me. Why? Because to ensure the sorted set only saves the latest 50 entries, I need to <code>zremrangebyrank</code> if the set cardinality exceeds 50. And that works only if <code>message_id</code> is the <code>score</code>, instead of the repeatable <code>user_id</code>. I hope that makes sense.</p>

<p>First, i think that you misunderstood the "NX" flag meaning. That is the sorted <strong>set</strong> - you can't have the same values with different scores. The "NX" flag only ensures, that if you will try to add value again with different score, then it will not modify the score of the existing element.</p>

<p>You need to use redis lists. You just need to add values like:</p>

<p>user_id:score_id (or serialized),</p>

<p>with: <a href="http://redis.io/commands/lset" rel="nofollow">http://redis.io/commands/lset</a></p>

<p>then use: <a href="http://redis.io/commands/lrange" rel="nofollow">http://redis.io/commands/lrange</a> to read last 50 elements, </p>

<p>and sometimes use: <a href="http://redis.io/commands/ltrim" rel="nofollow">http://redis.io/commands/ltrim</a> to trim the list.</p>

python redis