How should I store JSON in redis?
This is how i stored json in redis cache
Models.Student.findAll({
where: {
id : req.params.id
}
}).then(doc => {
client.setex(req.params.id, 3600, doc);
res.send(200, doc);
}).catch(err =>{
console.log(err);
res.send(400, err);
});
You could use this library redis-json
Sample usage example:
import Redis from 'ioredis';
import JSONCache from 'redis-json';
const redis = new Redis();
const jsonCache = new JSONCache(redis)
const user = {
name: "test",
age: 21,
gender: "male"
}
await jsonCache.set('123', user)
const result = await jsonCache.get('123')
This library stores the json in Hash set.
It also supports retreival of a single or a set of keys, i.e.
await jsonCache.get('123', "age", "name")
The RedisJSON module allows storing, updating and fetching JSON values from Redis keys.
It adds a new JSON datatype and commands to Redis which can be accessed like any other Redis native commands.
e.g.
> JSON.SET user1 $ '{"name":"Ron Dan", "lastSeen":1478476800, "loggedOut": true}'
OK
> JSON.GET user1 $.name
"[\"Ron Dan\"]"
> JSON.NUMINCRBY user1 $.lastSeen 100
"[1478476900]"
You can store JSON in redis either as a plain string in dedicated key (or member/value of a set/list) or in a hash structure. If you look at node_redis docs into Friendlier hash commands part you'll see that it gives you some useful methods for manipulating JSON based data. Pros of this approach is that it allows you to get/set only part of the original object and it might also consume less memory compared to plain strings.