Happydevdays Happydevdays - 3 months ago 20
reST (reStructuredText) Question

redis database design - determining the proper data type and creating secondary indexes

i have the following data that looks like this:

{
location: 'zimbabwe',
phone_num: 123-123-1234,
ext: 2222
}


or

{
location: 'puerto rico',
phone_num: 222-222-2222,
ext: 8888
}


My end users need to be able to query a REST API and send something like this:

http://myapp/internalext/123-123-1234

that should return an internal extension value of 2222.

But I also need to be able to support a query like this:

http://myapp/phonenumber/2222@abc.com

That should return to me a value of 123-123-1234

In order to be able to support queries like this, I'd like to know what the best way is for creating my data in redis. I have to create a node-redis web api.

So far, I've tried creating data like this:

127.0.0.1:6379> set phone:1
"{\"id\":1, \"locid\":1, \"loc_name\":\"zimbabwe\", \"extension\":\"2222\", \"e164\":\"1231231234\"}"


And then I created a secondary index referencing the same phone object:

127.0.0.1:6379> hset phone:lookup:e164 1231231234 1


Now, when I query, I have to do two lookups to find the ifnormation I want. So if the user passes me the full phone number, I have to do the following queries:

1. First lookup using the e164 as key:
127.0.0.1:6379> hget phone:lookup:e164 1231231234
"1"

2. now you know that it's the first key in the "phone" set(?? i dunno if this is the terminology)

127.0.0.1:6379> get phone:1
"{\"id\":1, \"locid\":1, \"loc_name\":\"zimbabwe\", \"extension\":\"2222\", \"e164\":\"1231231234\"}"
127.0.0.1:6379>


QUESTIONS

Is this the best way to organize / create my redis data for these types of GET requests?
I'm just reading about hashes. But I'm not familiar enough to know which way to proceed.
Also, given the above data, how would i request to see all phone numbers and their data?

Answer

I would use a HMSET to store the entire record, then simple key/value to query the data. For example:

HMSET 123-123-1234 location "zimbabwe" phone_num "123-123-1234" ext "2222"
HMSET 222-222-2222 location "puerto rico" phone_num "222-222-2222" ext "8888"

SET ext:2222 123-123-1234
SET ext:8888 222-222-2222

To get 123-123-1234 you use:

GET ext:2222

Given the number to get ext or location:

HMGET 123-123-1234 ext 
HMGET 123-123-1234 location