Slow Harry
Slow Harry

Reputation: 1897

Redis store location of users strategy

I want to store users locations(long,lat) in redis database. In my initial idea the keys will be users ids. I need 2 functionality: set location , get all locations. How should I perform it, or in which structure should I store it to easy and fast access.

Upvotes: 1

Views: 483

Answers (1)

Nick Bondarenko
Nick Bondarenko

Reputation: 6371

Looks like SETS is an good idea (if need location uniqueness):

  • UserId as key.
  • SADD for set location (require O(N) where N is the number of members to be added)
  • SMEMBERS for get all locations feature.
  • Hold long, lat as some delimiter separated string or serialized value (json for example).

PHP sample

$location = json_encode(array('long' => '...', 'lat' => '...'));
$redis->sAdd('locations:' . $userId, $location);
...
$redis->sAdd('locations:' . $userId, $location2);
...
$redis->sAdd('locations:' . $userId, $location2);
...
$userLocations = $redis->sMembers('locations:' . $userId); 

You did not say this, but if do not need uniqueness of locations the LISTS would be best choise:

  • RPUSH for set location (require O(1))
  • LRANGE for get all locations feature.
  • Key and value format like in SETS case.

PHP sample

$location = json_encode(array('long' => '...', 'lat' => '...'));
$redis->rPush('locations:' . $userId, $location);
...
$redis->rPush('locations:' . $userId, $location2);
...
$redis->rPush('locations:' . $userId, $location2);
...
$userLocations = $redis->lRange('locations:' . $userId, 0, -1);

If user has only one location HASH would be best choise:

  • One key for all users, for example locations
  • HSET where field is your userId and value is serialized data

PHP sample

$location = json_encode(array('long' => '...', 'lat' => '...'));
$redis->hSet('locations', $userId, $location);
...
$userLocation = json_decode($redis->hGet('locations', $userId));

Upvotes: 1

Related Questions