Michele
Michele

Reputation: 1488

Querying arrays in Redis with Predis

I want to to store and "SELECT" arrays in Redis with Predis, I entered data as follow:

$redis->hset("account_id_".$account_id, "access_time", time());

So I have this structure stored in redis

db0
    account_id_1
        access_time: 1400901850
        ...
        other values
    account_id_2
        access_time: 1400901862
        ...
        other values
    ...
    other_accounts

I want to select all accounts in a range of unix timestamps but I haven't find a way so far, I'm in doubt if the data structure is correct for this purpose.

Upvotes: 0

Views: 1295

Answers (1)

user142162
user142162

Reputation:

i'm in doubt if the data structure is correct for this purpose.

Your use of a hash is fine for storing the account data, but you need to make use of another data structure if you want better than O(N) lookup on the access_time field. Namely, you should use a sorted set.

You should have an additional key in your database called account:access_time of type sorted set. When an account is accessed, the following redis command should be run (with the appropriate variables filled in, of course):

ZADD account:access_time $access_time $account_id

Later on when you want to do a lookup based on access time, run the following:

ZRANGEBYSCORE account:access_time $min_access_time $max_access_time

The above command will return a list of account IDs that you can then do your work on.

Upvotes: 2

Related Questions