Reputation: 1897
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
Reputation: 6371
Looks like SETS
is an good idea (if need location uniqueness):
SADD
for set location (require O(N) where N is the number of members to be added) SMEMBERS
for get all locations feature.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)) 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:
locations
HSET
where field is your userId and value is serialized dataPHP sample
$location = json_encode(array('long' => '...', 'lat' => '...'));
$redis->hSet('locations', $userId, $location);
...
$userLocation = json_decode($redis->hGet('locations', $userId));
Upvotes: 1