问题如题,注意不是指模糊查询Key,是指对值的模糊(关键字)查询。
举个栗子:
$ HMSET user:1 name jack age 18
$ HMSET user:2 name jackson age 21
$ HMSET user:3 name suse age 16
假如有上述用户数据,以哈希形式存储,如果要做排序,可以
# score为#age,value为#userId,以ZSET结构存储
$ ZADD user:rank:age 18 1 21 2 16 3
# 查询有序列表
$ ZRANGE user:rank:age 0 -1
但如果需要既实现根据年龄排序,还要能够实现关键字查询(模糊匹配用户名),应该怎样实现?
淡淡烟草味2017-04-24 16:02:35
There is an alternative method, which can achieve simple and small data volume fuzzy query to a certain extent:
When writing user information, split the user name into a Key to record the user ID
SADD user:like:j jack jackson
SADD user:like:ja jack jackson
SADD user:like:jac jack jackson
SADD user:like:jack jack jackson
SADD user:like:jacks jackson
SADD user:like:jackso jackson
SADD user:like:jackson jackson
When performing fuzzy query later, enter: j
,则可以从SET
集合中查出jack
、jackson
two items. Of course, these two values can be replaced by user ID, and then the user hash information is queried based on the user ID.
This method is only suitable for scenarios where the query condition is single and the field length is short. If you fuzzy match the post title and post article at the same time, it will not work. You can still try the title, but the content will definitely not be achieved.
Of course, Redis is not inherently suitable for this, so if there are other solutions, it is recommended to use other solutions to achieve it.
巴扎黑2017-04-24 16:02:35
The euphemistic way is to write the Lua script yourself.
Or if the data set is not large, filter it yourself on the client side.
If fuzzy query is a hard requirement, it is recommended to move to Solr or Elasticsearch to do it.
黄舟2017-04-24 16:02:35
Redis does not have such rich query methods, and fuzzy query can only be performed in key, which cannot meet your rich needs. If you want high-speed storage, it is recommended to use Redis. If you want to perform business logic and have rich query methods, it is recommended to use MongoDb