如何在redis中存储哈希数组

发布于 2024-11-14 14:08:27 字数 36 浏览 6 评论 0原文

我想在 redis 中存储哈希数组,编码的最佳方法是什么?

I want to store array of hashes in redis , what is best way to code it ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一杯敬自由 2024-11-21 14:08:27

AFAIK 的唯一方法是取消引用它们。假设您有一个包含 2 个哈希值的数组,例如:{foo: 'bar', baz: 'qux'}

您可以单独存储它们,然后创建一个引用它们的集合:

HMSET myarr:0 foo bar baz qux
SADD myarr myarr:0
HMSET myarr:1 foo bar baz qux
SADD myarr myarr:1

然后您可以通过查询集合来检索它们:SMEMBERS myarr,然后调用HGETALLHGETALLcode> 在所有返回的键上重建原始哈希数组。

我希望这是有道理的。如果您找到更聪明的方法,我会很高兴听到。

The only way AFAIK is to de-reference them. Say you have an array of 2 hashes like: {foo: 'bar', baz: 'qux'}.

You'd store them separately, and then create a SET that references them all:

HMSET myarr:0 foo bar baz qux
SADD myarr myarr:0
HMSET myarr:1 foo bar baz qux
SADD myarr myarr:1

Then you can retrieve them all by querying the set: SMEMBERS myarr and then call HGETALL <key> on all the returned keys to rebuild your original array of hashes.

I hope this makes sense. And if you find a smarter way I'd be happy to hear it.

噩梦成真你也成魔 2024-11-21 14:08:27

如果您使用的语言支持 json 转换,则可以将哈希转换为 json 并将其附加到列表中。您可以在 Ruby 中执行以下操作:

require 'rubygems'
require 'redis'
require 'json'
require 'pp'

redis = Redis.new(:host => '127.0.0.1', :port => 6379)

h1 = { :k1 => 'v1', :k2 => 'v2' }
redis.rpush('arr', h1.to_json)

h2 = { :k3 => 'v3', :k4 => 'v4' }
redis.rpush('arr', h2.to_json)

hashes = redis.lrange('arr', 0, -1)
hashes.map! { |x| JSON.parse(x) }
pp hashes

If you are using a language which supports to/from json conversion, you can convert your hash to json and append it in a list. You can do the following in Ruby:

require 'rubygems'
require 'redis'
require 'json'
require 'pp'

redis = Redis.new(:host => '127.0.0.1', :port => 6379)

h1 = { :k1 => 'v1', :k2 => 'v2' }
redis.rpush('arr', h1.to_json)

h2 = { :k3 => 'v3', :k4 => 'v4' }
redis.rpush('arr', h2.to_json)

hashes = redis.lrange('arr', 0, -1)
hashes.map! { |x| JSON.parse(x) }
pp hashes
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文