按值查找键 [英] Find key by value

查看:29
本文介绍了按值查找键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现的想法是一个 id 表.基本上它有这样的结构 (user_id,lecturer_id),其中 user_id 指的是我的 User 表中的主键,而 Lecter_id 指的是我的 Lecturer 表中的主键.

The think I'm trying to implement is an id table. Basically it has the structure (user_id, lecturer_id) which user_id refers to the primary key in my User table and lecturer_id refers to the primary key of my Lecturer table.

我正在尝试在 redis 中实现这一点,但是如果我将密钥设置为用户的主 ID,那么当我尝试运行类似获取所有讲师 id=5 的记录 之类的查询时,因为讲师是不是关键,而是价值我将无法在 O(1) 时间内达到它.

I'm trying to implement this in redis but if I set the key as User's primary id, when I try to run a query like get all the records with lecturer id=5 since lecturer is not the key, but value I won't be able to reach it in O(1) time.

如何形成我上面提到的 id 表这样的结构,否则 Redis 不支持?

How can I form a structure like the id table I mentioned in above, or Redis does not support that?

推荐答案

在使用 redis 时,您可以快速学到的一件事是您可以围绕访问需求设计数据结构,特别是在涉及关系时(它是毕竟不是关系数据库)

One of the things you learn fast while working with redis is that you get to design your data structure around your accessing needs, specially when it comes to relations (it's not a relational database after all)

正如您已经注意到的那样,无法按 O(1) 时间复杂度按值"进行搜索,但是有一些方法可以使用 redis 来处理您所描述的内容.以下是我的建议:

There is no way to search by "value" with a O(1) time complexity as you already noticed, but there are ways to approach what you describe using redis. Here's what I would recommend:

  • 按用户 ID(例如哈希)存储您的用户数据,就像您已经在做的那样.
  • 为每个讲师 ID 设置一个额外的集合,其中包含与相关讲师 ID 对应的所有用户 ID.

这可能看起来像是复制关系的数据,因为您的用户数据必须存储讲座 ID,而您的讲座数据将存储用户 ID,但如果要建立关系,这是(微小的)代价在像redis这样的非关系数据存储中.实际上,这很有效;内存很少成为小型数据集的瓶颈(想想数千个 ID).

This might seem like duplicating the data of the relation, since your user data would have to store the lecture id, and your lecture data would store user ids, but that's the (tiny) price to pay if one is to build relations in a no-relational data store like redis. In practical terms this works well; memory is rarely a bottleneck for small-ish data-sets (think thousands of ids).

为了更好地了解人们如何使用 redis 为具有关系的应用程序建模,我建议阅读 Design and一个简单的 Twitter 克隆的实现Lamernews 的源代码,两者都是由redis 作者 Salvatore Sanfilippo.

To get a better picture at how are people using redis to model applications with relations, I recommend reading Design and implementation of a simple Twitter clone and the source code of Lamernews, both of which are written by redis author Salvatore Sanfilippo.

这篇关于按值查找键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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