数据库 - 请问redis遇到条件查询怎么办呢?
巴扎黑
巴扎黑 2017-04-21 11:16:04
0
1
743

我是新手刚想学redis,但是看了很多资料都在说redis怎么快怎么快,很少说具体怎么应用到项目上的,就算有也是做队列或是缓存用。看了看redis入门资料也说redis只支持k->v类型的数据保存且没有条件查询,那如果遇到条件查询了怎么办呢?如保存了一些对象:a{name:lijiang age:60 } 请问怎么查询所有姓li的用户或所有年龄是60的用户呢?

巴扎黑
巴扎黑

reply all(1)
小葫芦

Fast comes at a price. redis is a non-relational database. To query based on conditions, you must manually create indexes for the data.

Hashset can be used to save objects. Assume that the hashset key is in the form 'user:name'.
Conditional queries can use sorted set. key is a field of the object. When searching for a name, you can use the zRangeByLex command:

redis> zadd personIndex:name 0 lijiang 0 likui 0 abcde
(integer) 3
redis> zRangeByLex personIndex:name [li (lj
1) "lijiang"
2) "likui"

After that, you can use user:lijiang and user:likui to get relevant information.

To find people whose names start with li, you can use '[li (lj') to find strings in the semi-open range [li..., lj). When redis compares a string and its prefix, the longer one is larger (for example: liA > li, liABCDEF... < lj).

(Note: zRangeByLex requires redis version >2.8.9)

To search for age conditionally, you can use the zRangeByScore command of sorted set:

redis> zadd personIndex:age 60 lijiang 30 likui 20 abcde
(integer) 3
redis> zRangeByScore personIndex:age 30 60
1) "likui"
2) "lijiang"

The three parameters of zRangeByScore are: key, min, max (closed interval)

Reference: http://redis.io/commands/

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template