Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple search by value?

Tags:

database

redis

I would like to store some information as follows (note, I'm not wedded to this data structure at all, but this shows you the underlying information I want to store):

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

In these records, user_id is a unique field, but the 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 searches as follows:

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

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

like image 543
Richard Avatar asked Oct 31 '11 12:10

Richard


2 Answers

It sounds like you need two key types: a HASH key to store your user's data, and a LIST for each page that contains a list of related users. Below is an example of how this could work.

Load Data:

> 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 GETs in the SORT to retrieve additional values for the user.

I hope this helps, let me know if there's anything you'd like clarified or if you need further assistance. I also recommend reading the commands list and documentation available at the redis web site, especially concerning the SORT operation.

like image 165
Zikes Avatar answered Oct 11 '22 11:10

Zikes


Since user_id is unique and so does country, keep them in a simple key-value pair. Quering for a user is O(1) in such a case... Then, keep some Redis sets, with key the page_id and members all the user_ids..

like image 32
hymloth Avatar answered Oct 11 '22 10:10

hymloth