Simple cost search?

I would like to save some information as follows (note that I am not tied to this data structure at all, but it shows you the basic information that I want to save):

{ user_id: 12345, page_id: 2, country: 'DE' }

In these entries, user_id is a unique field, but page_id is not.

I would like to translate this into a Redis data structure, and I would like to be able to run efficient search queries as follows:

  • For user_id 12345, find the appropriate country.
  • For page_id 2, find all related user_id and their countries.

Is it possible to do this in Redis? If so, what data structures should I use, and how should I avoid the possibility of duplicate records when I insert them?

+5
source share
2 answers

It looks like you need two types of keys: a HASH key to store your user data and a list for each page containing a list of related users. Below is an example of how this might work.

Data loading:

> RPUSH page:2:users 12345
> HMSET user:12345 country DE key2 value2

Pull data:

# All users for page 2
> LRANGE page:2:users 0 -1

# All users for page 2 and their countries
> SORT page:2:users By nosort GET # GET user:*->country GET user:*->key2

Remove user from page:

> LREM page:2:users 0 12345

Repeat GET in SORT to get additional values โ€‹โ€‹for the user.

I hope this helps, let me know if there is anything you would like to clarify, or if you need further assistance. I also recommend reading the list of commands and documentation available on the redis website , especially regarding the SORT operation.

+4
source

user_id , , -. - O (1) ... Redis page_id user_ids..

+1

All Articles