首页 > 解决方案 > 在 Redis 中根据对象的两个属性进行查询的正确数据结构是什么

问题描述

我是 Redis 新手,希望从专家那里获得有关我的用例的建议。我有一个事件对象,它具有 start_time_of_event 和 end_time_of_event 作为两个属性(对象中有更多属性)。我有数百万个这样的事件,需要将它们存储在 Redis 中,以便我可以在运行时查询它们。我希望将时间戳用作键,将事件对象用作值。查询时,我需要从现在开始获取 start_time_of_event <= current_time 和 end_time_of_event>=1 周的事件列表。不确定 Redis 中的 ZRANGE、LRANGE 或任何其他数据结构是否支持使用多个(复杂)键。关于使用 Redis 实现上述用例的最佳方法是什么?

提前非常感谢。

标签: cachingdata-structuresredis

解决方案


您应该将事件存储在两个 Redis ZSET 中,一个设置得分应该是start_time_of_event,另一个得分应该是end_time_of_event

让我们分别称它们为start_eventsend_events

添加:

ZADD start_events start_time event
ZADD end_events end_time event

搜索

-- randomly generate a destination id, search the events 
-- and store in that based on the start time

ZRANGESTORE random-start-time-dst start_events 0 current_time

-- randomly generate a destination id for end-time search, post filter 
-- store results in that destination

ZRANGESTORE random-end-time-dst end_events current_time+7.weeks -1

-- Take the intersection of these two sets
ZINTER INT_MAX random-start-time-dst random-end-time-dst 

-- Delete the newly created collections to  free up the memory 
DEL random-start-time-dst
DEL random-end-time-dst

推荐阅读