Aerospike-在嵌套对象中添加新的键/值对

时间:2018-10-16 13:10:26

标签: node.js json nested aerospike

在Aerospike中,如何在存储在map类型的容器中的嵌套对象中添加新的键/值对?

例如, 我有一个类型映射的容器,需要将其存储在键/值对下面。

{
  "a" : "apple",
  "b" : "ball",
  "c" : { "d" : "dog", "e" : "elephant" }, 
  "f" : { "g" : { "h" : "horse" } },
  "i" : { "j" : "jackal", "k" : { "l" : "lion", "m" : "monkey" } }
}  

现在,我想针对键“ k”更新一个现有的嵌套对象,以添加如下所示的另一个键值对。

"k" : { "l" : "lion", "m" : "monkey", "n" : "nest" }

最终结果应如下所示。

{
  "a" : "apple",
  "b" : "ball",
  "c" : { "d" : "dog", "e" : "elephant" }, 
  "f" : { "g" : { "h" : "horse" } },
  "i" : { "j" : "jackal", "k" : { "l" : "lion", "m" : "monkey", "n" : "nest" } }
}  

关于如何实现此目标的任何建议? 这是一个NodeJS(10.6.0)应用程序,我正在使用NodeJS aerospike客户端(3.6.1)与Aerospike(4.3.0.7)进行交互。

2 个答案:

答案 0 :(得分:8)

现在可以使用Aerospike server version 4.6或更高版本以及Aerospike Node.js client version 3.12或更高版本来更新嵌套CDT映射和列表。该更新在列表和映射操作中引入了withContext() function,使您可以指定要在其中执行列表/映射操作的上下文。您可以在新CdtContext class的文档中找到更多信息。

这是您执行示例中给出的更新的方式:

const Aerospike = require('aerospike')
const maps = Aerospike.maps

Aerospike.connect().then(async (client) => {
  const key = new Aerospike.Key('test', 'test', 'test')

  const map = {
    "a" : "apple",
    "b" : "ball",
    "c" : { "d" : "dog", "e" : "elephant" },
    "f" : { "g" : { "h" : "horse" } },
    "i" : { "j" : "jackal", "k" : { "l" : "lion", "m" : "monkey" } }
  }
  console.log('BEFORE:', map)
  await client.put(key, map)

  await client.operate(key, [
    maps.put('i', 'n', 'nest')
        .withContext((ctx) => ctx.addMapKey('k'))
  ])
  const record = await client.get(key)
  console.log('AFTER:', record.bins)

  client.close()
}).catch((error) => {
  console.error(error)
  if (error.client) error.client.close()
})

运行示例时,您将获得以下内容:

$ node nested-map-update-example.js
BEFORE: {
  a: 'apple',
  b: 'ball',
  c: { d: 'dog', e: 'elephant' },
  f: { g: { h: 'horse' } },
  i: { j: 'jackal', k: { l: 'lion', m: 'monkey' } }
}
AFTER: {
  a: 'apple',
  b: 'ball',
  c: { d: 'dog', e: 'elephant' },
  f: { g: { h: 'horse' } },
  i: { j: 'jackal', k: { l: 'lion', m: 'monkey', n: 'nest' } }
}

答案 1 :(得分:3)

您将必须更新键“ i”的完整值。

相关问题