如何在Redis中存储对象数组? [英] How to store array of objects in Redis?

查看:588
本文介绍了如何在Redis中存储对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要存储在 Redis 中的对象.我可以分解数组部分并将它们存储为对象,但我不知道如何获得

I have an array of Objects that I want to store in Redis. I can break up the array part and store them as objects but I am not getting how I can get somethings like

{0} : {"foo" :"bar", "qux" : "doe"}, {1} : {"name" "Saras", "age" : 23} 

然后根据名称搜索数据库并取回请求的密钥.我需要这样的东西.但不能接近正确.

and then search the db based on name and get the requested key back. I need something like this. but can't come close to getting it right.

incr id //correct
(integer) 3
get id //correct
"3"
SADD id {"name" : "Saras"} //wrong 
SADD myset {"name" : "Saras"} //correct
(integer) 1

首先是正确处理这部分.

First is getting this part right.

其次是以某种方式从值中获取密钥,即

Second is somehow getting the key from the value i.e.

if name==="Saras"  
then key=1

我觉得这很难.或者我可以将它直接存储为对象数组并使用简单的 for 循环.

Which I find tough. Or I can store it directly as array of objects and use a simple for loop.

 for (var i = 0; i < userCache.users.length; i++) {
            if (userCache.users[i].userId == userId && userCache.users[i].deviceId == deviceId) {
                return i;
            }
        }

请建议哪种路线最适合某些实施?

Kindly suggest which route is best with some implementation?

推荐答案

我发现的工作是将键存储为唯一标识符,并在存储数据时对整个对象进行字符串化,并在提取数据时应用 JSON.parse.

The thing I found working was storing the key as a unique identifier and stringifying the whole object while storing the data and applying JSON.parse while extracting it.

>

示例代码:

client
    .setAsync(obj.deviceId.toString(), JSON.stringify(obj))
    .then((doc) => {
        return client.getAsync(obj.deviceId.toString());
    })
    .then((doc) => {
        return JSON.parse(doc);
    }).catch((err) => {
        return err;
    });

虽然字符串化然后解析它是一个计算量很大的操作,如果 JSON 的大小变大,它将阻塞 Node.js 服务器.我可能已经准备好接受较低的复杂性,因为我知道我的 JSON 不会很大,但是在采用这种方法时需要牢记这一点.

Though stringifying and then parsing it back is a computationally heavy operation and will block the Node.js server if the size of JSON becomes large. I am probably ready to take a hit for lesser complexity because I know my JSON wouldn't be huge, but that needs to be kept in mind while going for this approach.

这篇关于如何在Redis中存储对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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