Reputation: 131
I started learning redis and nodejs , I am getting data from third party api call. I want to save this data into my redis server. I am able to do that but I got a problem that if i get data in json array with multiple keys I am not able to insert it. How can I solve this issue?
My data is:
keys
[123,3435,455,455]
value
[{name:'shakti'},{name:'amit'},{name:'amiit'},{name:'sad'}]
I want to save this data at once in to key value form without using any for loop. Currently I am using for loop like
for(var i=0i<keys.length;;i++){
redisClient.set(keys[i],data);
}
Please help me to solve this. Thanks
Upvotes: 10
Views: 8183
Reputation: 1273
I did the same thing in my app. I was trying to save each record by unique placeId
. My records are
[
{
"name": "Ranchi Railway Station",
"placeId": "RAIL001",
"category": "railway",
"latitude": 3.09072,
"longitude": 101.70076
},
{
"name": "Delhi Airport",
"placeId": "AIR129",
"category": "airport",
"latitude": 4.09072,
"longitude": 100.70076
}
]
I wanted to save each record fetched from the query by using placeId
to the redis at once. I used the following way to cache those records.
const placesRecords = {};
places.forEach((element) => {
placesRecords[element.placeId] = JSON.stringify(element);
});
redisClient.mset(placesRecords, (err, reply) => {
if(err) {
console.log(" err: " + err);
} else {
console.log(" reply: " + reply);
}
});
Upvotes: 6
Reputation: 6764
Use MSET
. In node-js:
var keys = [123,3435,455,455]
var values = [{name:'shakti'},{name:'amit'},{name:'amiit'},{name:'sad'}]
var arr = [];
for (var i = 0; i < keys.length; i++) {
arr.push(keys[i]);
arr.push(JSON.stringify(values[i]));
}
client.mset(arr, function(err, reply) {
console.log(" reply: " + reply);
console.log(" err: " + err);
client.quit();
});
Upvotes: 5