How to store array of objects in Redis?

拟墨画扇 提交于 2019-12-01 19:45:12

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.

Example code:

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;
    });

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 is pretty simple key-value storage. Yes, there are other data structures like sets, but it has VERY limited query capabilities. For example, if you want to get find data by name, then you would have to to something like that:

SET Name "serialized data of object"

SET Name2 "serialized data of object2"

SET Name3 "serialized data of object3"

then:

GET Name

would return data.

Of course this means that you can't store two entries with the same names.

You can do limited text matching on keys using: http://redis.io/commands/scan

To summarize: I think you should use other tool for complex queries.

The first issue you have, SADD id {"name" : "Saras"} //wrong, is obvious since the "id" key is not of type set, it is a string type.

In redis the only access point to data is through its key. As kiss said, perhaps you should be looking for other tools.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!