Search code examples
cachingredisazure-redis-cache

Redis - best way to cache nested data structure with dates


I need to find the most efficient way to cache the result from an endpoint that returns pricing for hotel rooms. The endpoint only returns data for one roomTypeId at a time, and the data returned is a list of { date : string, roomTypeId: string, price: { price: number, currency: string }[] }

I need to access it from the cache like this: getPrice(roomTypeIds, fromDate, toDate).

I’m new to Redis, but I’ve read up on sorted sets, which seems like a good fit since it will make it easy to return dates within a range. But since I have to return the pricing for multiple room type ids, I’m guessing I would need to have a set per room type id, which makes it a bit more complex.

Does anybody have any good sugestions on how to store a data structure like this? (I’m using TypeScript)


Solution

  • Sorted set can do it for you!

    Add elements into the cashe with:

    ZADD roomTypeId date "{your json}"
    

    Now you are ready to get your filtered results:

    ZRANGE roomTypeId fromDate toDate BYSCORE
    

    Note: fromDate, toDate and date should be lexicographically sortable! Using just timestamp for that purpose will do.

    It might be inciteful to look also at documentation: ZADD Command ZRANGE Command