gpt4 book ai didi

redis - 在 Redis 中使用 WHERE 子句查询值

转载 作者:IT王子 更新时间:2023-10-29 05:58:43 26 4
gpt4 key购买 nike

我正在学习redis,有一个初学者的问题。我知道redis就是关于键的!有什么方法可以查询/解析特定内容的键值吗?

假设我有键和一些 json 作为值。例如

key1 = {"id":"1", "colour":"red}
key2 = {"id":"2", "colour":"green}
key3 = {"id":"3", "colour":"red}

我如何查询所有具有 colour=red 的“值 (jsons)?

select all values WHERE colour==red

最佳答案

您需要的是 colour 字段上的反向索引,即映射 colour -> {keyA, ..., keyB},例如 "red"-> {key1, key2}

您可以使用 Redis set维护此索引,如 Ohm 所解释的那样:

A set in Redis is an unordered list [...] It's used internally by Ohm to keep track of the instances of each model and for generating and maintaining indexes.

另见 answer迪迪埃·斯佩齐亚 (Didier Spezia) 着。

总结一下:以您查询数据的方式存储数据

欧姆示例

以下是 Ohm 在幕后发生的事情。

首先声明您的 Ohm 模型,并索引 colour 属性,因为您要查询它:

require "ohm"

class Doc < Ohm::Model
attribute :colour
index :colour
end

然后创建一些文档:

ruby> Doc.create(:colour => "red")
ruby> Doc.create(:colour => "green")
ruby> Doc.create(:colour => "red")

在这一步检查相关索引中存储的欧姆:

redis> SMEMBERS "Doc:indices:colour:red"
1) "1"
2) "3"

再创建一个红色文档:

ruby> Doc.create(:colour => "red")

重新检查索引:

redis> SMEMBERS "Doc:indices:colour:red"
1) "1"
2) "3"
3) "4"

索引已更新以反射(reflect)最后一条记录。

现在您可以高效地查询您的文档:

ruby> Doc.find(:colour => "red").each {|d| puts d.id}
1
3
4

关于redis - 在 Redis 中使用 WHERE 子句查询值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19285804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com