如何在redis中搜索哈希键? [英] How to search in redis for hash keys?

查看:70
本文介绍了如何在redis中搜索哈希键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用哈希键来存储用户详细信息,例如:

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

我需要搜索具有 age = 25name = lee 的用户.如何在给定字段中搜索指定值?

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

推荐答案

你不能.Redis 是键值存储,而不是关系型数据库.

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

为了搜索特定数据,您需要构建该数据的访问路径.例如,要获取年龄 = 25 的用户,您需要构建一个索引以将年龄值映射到用户.它可以用一组来完成.这与名称相同.

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

这篇关于如何在redis中搜索哈希键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆