Node js redis set data at once
Asked Answered
K

2

10

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

Kilbride answered 28/12, 2018 at 20:24 Comment(1)
yes , you can save json for multiple keys, this may help you: redislabs.com/blog/redis-as-a-json-storeWaffle
S
6

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);
  }
});
Suavity answered 11/6, 2020 at 8:52 Comment(0)
A
5

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();
});
Armful answered 20/1, 2020 at 23:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.