Reputation: 335
Just starting out with Redis and incorporating it into a Node+Express app.
I'm currently using Redis to store third-party API results to cutdown on requests made by my app.
Example: User searches "California", my app checks if this query already exists in the Redis db, and grabs the relevant JSON object if it does. If not, Redis sets the key (the query) and the value (the JSON object from the third party API).
I'd like to be able to rank the queries made. Say "California" is searched 4 times while "Montana" is only searched once--I'd want to return "California".
What's the best way to gather a rank for the most popular searched keys?
The closest I could find was this, but sorted sets don't seem to allow for a key AND value. It's just a value and score.
Upvotes: 0
Views: 390
Reputation: 38989
Use a sorted set to sort the keys, then have an auxiliary hash that stores the values. Example:
ZADD myzset 4 "california" 1 "montana"
HSET myzset:aux_hash "california" "some api result"
HSET myzset:aux_hash "montana" "some other api result"
Then, if more searches happen for California, for example, use ZINCRBY
to increase its score: ZINCRBY myzset 1 "california"
Finally, when a user queries for something, check if it's in myzset
(ZSCORE myzset "california"
-- verify this is not nil). If it exists, just grab the value from the auxiliary hash (HGET myzset:aux_hash "california"
) and return that to the user. For the last two steps, you can throw them into a Lua script to only hit the server once and speed things up, if you like.
Upvotes: 1