从redis获取最新的set/hash
我刚刚开始使用 redis,并且在使用 noSql 时遇到了第一个绊脚石;以前我只知道 SQL Server。
我理解一切都是基于键值的原则。但是它如何与排序一起使用,例如:
使用哈希集:
HMSET users:1 firstname 'james' lastname 'smith' created 'datetime.datatime.now'
现在我假设您添加第二条记录,您将获得哈希集的长度(在这种情况下,我们会说它的 1 返回值 x
),然后添加另一行:
HMSET users:x firstname 'john' lastname 'smith' created 'datetime.datatime.now'
您如何获取最新记录?按日期?或者你可以直接说“获取哈希集-1处的记录”吗?
当排序集更合适时,我可能建议使用哈希集?
I'm just getting started with redis and I've hit my first stumbling block with going noSql; previously all I've known is SQL server.
I understand the principle that everything is key value based. But how does that work with ordering, for example:
Using a hash set:
HMSET users:1 firstname 'james' lastname 'smith' created 'datetime.datatime.now'
Now I assume you to add a second record you would get the length of the hash set (in this case we shall say its 1 returned to value x
), then add another row:
HMSET users:x firstname 'john' lastname 'smith' created 'datetime.datatime.now'
How would you get the latest record? By date? Or can you just say 'get record at -1 of hashset'?
Possibly I'm proposing to use a hashset when a sorted sets are more appropriate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要检查 SORT 命令。
如果创建时间戳存储在纪元时间中,则可以按创建时间戳排序。
如果需要,您可以获取多个密钥,SORT 可能是具有大多数选项的命令,请研究文档。
关于密钥,你必须仔细考虑可能的密钥重用(删除,计数+1,插入会重用密钥?),所以我只是从我的项目中的关系数据库中获取密钥。
You will want to check the SORT command.
You can sort by create timestamp if that is stored in epoch time.
You can get multiple keys if you want, SORT is probable the command with most options, study the doc.
About the keys, you have to think carefully about possible key reuse (delete, count+1, insert would reuse the key?), so I just get the keys from relational database in my project.
您应该使用一组已排序的用户 ID,当您添加到该组时,添加用户 ID 和时间戳作为分数。
然后,您可以使用 zrevrange 等按升序或降序顺序将它们拉出,将其限制为 1 条记录以获得最新记录。
然后你就可以从哈希中获取所有值。
You should use a sorted set of userids, when you add to the set, add the userid and the the timestamp as the score.
Then you can pull them out in asc or desc order using something like zrevrange, limit this to 1 record to get your latest.
Then you can get all the values from your hash.