简体   繁体   English

如何使用nodejs在redis中插入对象数组

[英]how to insert array of object in redis using nodejs

here is the array of object,want to store in redis by mapping and grouping on categoryId这里是对象数组,希望通过在categoryId上映射和分组存储在redis中

var cars = [
{
    'category': 1,
    'model': 'r8',
    'year': '2012'
}, {
    'category': 1,
    'model': 'rs5',
    'year': '2013'
}, {
    'category': 2,
    'model': 'mustang',
    'year': '2012'
}, {
    'category': 2,
    'model': 'fusion',
    'year': '2015'
}, {
    'category': 3,
    'model': 'optima',
    'year': '2012'
} ];

and i want to store in redis(hmset) suppose the key name is item,我想存储在 redis(hmset) 中,假设键名是 item,

1: [
    {   'categoryId':1
        'model': 'r8',
        'year': '2012'
    }, { 'categoryId':1
        'model': 'rs5',
        'year': '2013'
    },
 ],
2: [
    {   'categoryId':2
        'model': 'mustang',
        'year': '2012'
    }, { 'categoryId':2
        'model': 'fusion',
        'year': '2015'
    }
],

3: [
    {   'categoryId':3
        'model': 'optima',
        'year': '2012'
    }
]

and so that i can fetch records on the basis of category id using hmget(item,2)这样我就可以使用 hmget(item,2) 根据类别 id 获取记录

for using Redis in node.js I install and require redis-async from npm为了在 node.js 中使用 Redis,我安装并需要来自 npm 的redis-async

I grouped input data with groupingCars() function.我使用groupingCars()函数groupingCars()输入数据进行groupingCars()

for insert data in to redis I user insertCars function.用于将数据插入到 redis 我使用insertCars函数。

for fetch data from Redis I user fetchCar function.为了从 Redis 获取数据,我使用了fetchCar函数。

var client = redis.createClient({
  host: "127.0.0.1", // hostname
  db: 0, //redis db
});
let groupedCars = [];
var cars = [
  {
    category: 1,
    model: "r8",
    year: "2012",
  },
  {
    category: 1,
    model: "rs5",
    year: "2013",
  },
  {
    category: 2,
    model: "mustang",
    year: "2012",
  },
  {
    category: 2,
    model: "fusion",
    year: "2015",
  },
  {
    category: 3,
    model: "optima",
    year: "2012",
  },
];
// grouping Cars based on Category
async function groupingCars() {
  cars.forEach((car) => {
    if (!groupedCars[car.category]) {
      groupedCars[car.category] = [];
    }
    groupedCars[car.category].push(car);
  });
}

//inserted each item into redis
async function insertCars() {
  groupedCars.forEach(async (gpCar, category) => {
    await client.hmset("item", category, JSON.stringify(gpCar));
  });
}

//fetch data from redis based on category
async function fetchData() {
  let result = await client.hmget("item", "1");
  result = JSON.parse(result)
  console.log(result);
}


groupingCars()
insertCars()
fetchCar();

Data Stored in Redis存储在 Redis 中的数据在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM