Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store simple arrays in Redis

Tags:

php

redis

I'd like to know what would be the best way to store IPs (not a lot of them (<50)) together with some meta data (time added, note) in Redis. I need to be able to quickly determine if some IP is in that list and be able to retrieve all stored IPs.

I have some ideas but they don't seem elegant/efficient to me:

  • Store IPs using lists where each entry is array (ip,note,timestamp). This would make retrieving of all the IPs simple, but would require looping trough all the IPs do determine if a given IP is in the list or not. So this is good to retrieve all IPs but not so good for checking for existence of one IP.
  • Store IPs using hash tables, where IP is part of the key, and meta data are fields in the hash. This would allow me to check if a IP is stored very simply (exists()), but would require a separate redis list to keep track of stored IPs (which would require for me to be very careful when adding/removing IPs) and I would have to execute 1 + count(ips) operations to get all stored IPs and their meta information. So this way is good for checking for existence of one IP but is not good for retrieving all IPs.

Is there some other way of doing this with redis or will I have to use one of the above approaches (if so, which one is the best)?

like image 763
Jan Hančič Avatar asked Apr 13 '12 13:04

Jan Hančič


2 Answers

For the your data size it will not really matter.

However how about this hack. Use an ordered set with the score being the IP (treat it as a number with each period being considered a 00, ex 127.0.0.1 => 1270000001) and each item being the metadata and the IP in JSON

zadd ip_set 1270000001 '{ip:"127.0.0.1", note:"blah"}

then to get all you just do

zrange ip_set 0 -1

and to check for presence

zcount ip_set 1270000001
like image 104
Dmytro Yashkir Avatar answered Sep 20 '22 16:09

Dmytro Yashkir


Second way of course. It's a key-value storage. You should use keys exactly how you described. Redis executes operations very quickly. Don't worry about 1-2 operations.

like image 27
Adelf Avatar answered Sep 20 '22 16:09

Adelf