在Redis上存储JSON数组

Store JSON array on Redis

本文关键字:JSON 数组 存储 Redis      更新时间:2023-09-26

我在javascript中有以下JSON数组:

[
    {
        title: 'Title 1',
        description: 'Description 1',
        startTime: 'Start time 1',
        duration: 5,
        humidity: 50
    },
    {
        title: 'Title 2',
        description: 'Description 2',
        startTime: 'Start time 2',
        duration: 15,
        humidity: 30
    },
    {
        title: 'Title 2',
        description: 'Description 2',
        startTime: 'Start time 2',
        duration: 10,
        humidity: 40
    }
]

我需要将其存储在Redis存储上。我需要能够在大多数情况下检索整个数组,但有时我需要获得特定的项。在SQL中,我可以创建一个自动递增的"ID",并将每个条目存储在一行中。但是用Redis实现这一目标的最佳方法是什么呢?

谢谢!

我在Redis中保存相同的结构。当您需要使用RedisJSON检索JSON格式的所有数据时,这是优化的。例如保存结构:

const tagsArray = {
      id: '101',
      qc: 3,
      ts: '2022-07-07T14:36:14.712Z',
      val: 10.332507886284837,
      tag: 'DB_right.Corrente'
    },
    { ... },
    { ... }
 }

我正在使用代码(例如:Node.js with redis npm module):

const redisClient = createClient()
await redisClient.connect()
await redisClient.json.set('arr:key', '$', [])
await redisClient.json.arrAppend('arr:key', '$', {searchKey: tagsArray})
const r = await redisClient.json.get('arr:key')
console.log('@R >> ', r)

您可以为JSON数组中的每个元素构建一个searchKey,您将用项目填充!