简体   繁体   English

在Redis中使用排序集的替代数据模型(对于Django / Python项目)

[英]Alternative data model to using sorted set in redis (for a Django/Python project)

I have a web application where users post text messages for others to read (kind of like Twitter). 我有一个Web应用程序,用户在其中发布文本消息以供他人阅读(类似于Twitter)。

I need to save the 50 latest message_id and the poster's user_id pairs (for processing later). 我需要保存50个最新的message_id和发布者的user_id对(以供以后处理)。 I use redis backend and realized I can save these 50 latest pairs in a sorted set: user_id as a value and message_id as a score. 我使用redis后端,并意识到我可以将这50个最新对存储在一个排序集中: user_id作为值和message_id作为得分。

Now since user_id can be repeated, I would need to set the NX flag to true . 现在,由于可以重复user_id ,因此我需要将NX标志设置为true This, according to the docs , ensures that new members are added to the sorted set instead of updating existing ones. 根据docs ,这可确保将新成员添加到排序后的集合中,而不是更新现有成员。 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. 这样可以使数据保持理智。

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). 问题出在这里:我的应用程序使用python,而Redis 2.8.4(我使用的版本)未引入NX标志。

So what alternatives do I have for efficiently saving the 50 latest message_id and user_id pairs using redis? 那么,我有什么替代方法可以使用Redis有效地保存50对最新的message_iduser_id对? Please advise. 请指教。


Switching message_id and user_id in the sorted set as value and score doesn't work for me. 将排序集中的message_iduser_id切换为值和分数对我不起作用。 Why? 为什么? Because to ensure the sorted set only saves the latest 50 entries, I need to zremrangebyrank if the set cardinality exceeds 50. And that works only if message_id is the score , instead of the repeatable user_id . 因为要确保排序后的集合仅保存最新的50个条目,所以如果集合的基数超过50,则需要zremrangebyrank 。这仅在message_idscore而不是可重复的user_id时才有效。 I hope that makes sense. 我希望这是有道理的。

First, i think that you misunderstood the "NX" flag meaning. 首先,我认为您误解了“ NX”标志的含义。 That is the sorted set - 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. “ NX”标志仅确保,如果您尝试再次添加具有不同分数的值,则不会修改现有元素的分数。

You need to use redis lists. 您需要使用redis列表。 You just need to add values like: 您只需要添加以下值:

user_id:score_id (or serialized), user_id:score_id(或已序列化),

with: http://redis.io/commands/lset 使用: http : //redis.io/commands/lset

then use: http://redis.io/commands/lrange to read last 50 elements, 然后使用: http : //redis.io/commands/lrange读取最后50个元素,

and sometimes use: http://redis.io/commands/ltrim to trim the list. 有时使用: http : //redis.io/commands/ltrim修剪列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM