Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

How to search in redis for hash keys?

I'm using hash keys to store user details like:

 hmset user:1 user_name lee  age 21
 hmset user:2 user_name david  age 25
 hmset user:3 user_name chris  age 25

I need to search for users having age = 25, name = lee. How to do a search for a specified value in a given field?

question from:https://stackoverflow.com/questions/11470468/how-to-search-in-redis-for-hash-keys

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot. Redis is a key-value store, not a relational database.

In order to search for a specific data, you need to build an access path to this data. For instance, to get the users having age = 25, you need to build an index to map the age values to users. It can be done with a set. This is the same for the name.

Once you have sets for age and name, you can search users by intersecting the sets. For example:

# Add 3 users
hmset user:1 user_name lee age 21
hmset user:2 user_name david age 25
hmset user:3 user_name chris age 25

# Maintain age index
sadd age:21 1
sadd age:25 2 3

# Maintain name index
sadd name:lee 1
sadd name:david 2
sadd name:chris 3

# Get the ID of users having age = 25 and name = lee
sinter age:25 name:lee
  -> will return an empty set

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...