Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js redis set data at once

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

like image 568
user3060781 Avatar asked Dec 28 '18 20:12

user3060781


People also ask

How set redis value in node JS?

Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.

How use redis node JS Express?

To use the Redis, you need to install Node JS Redis Client in the local system. The msi file (v3. 0.504 stable version as of this article published date) can be downloaded from the Github and proceed with normal installation process (for Windows OS).

What is MSET in redis?

Redis MSET command is used to set multiple values to multiple keys. It replaces existing values with new values. Syntax: MSET key1 value1 key2 value2 .. keyN valueN.


2 Answers

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);
  }
});
like image 104
pravindot17 Avatar answered Sep 21 '22 07:09

pravindot17


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();
});
like image 24
LeoMurillo Avatar answered Sep 20 '22 07:09

LeoMurillo