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

标签 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) 进行交互。

最佳答案

现在可以使用 Aerospike server version 4.6 更新嵌套的 CDT map 和列表。或更高版本和Aerospike Node.js client version 3.12或以后。该更新引入了 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' } }
}

关于node.js - Aerospike - 在嵌套对象中添加新的键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52836233/

相关文章:

javascript - 带有 Node 集群模块的 Socket.io

json - 使用 json4s.replace 替换 Json AST 中的对象

java - 扩展内部类和扩展嵌套类之间的区别?

jquery - 服务器端jquery

javascript - 使用 import 从 ES6 中的 cwd() 读取

python - 使用 Flask-Restful 的字段,如何获得 "catchall"字段?

jquery - getJSON 返回错误 'object is undefined'

JavaScript 基础知识 : accessing nested-functions

angular - 在 Angular 中创建嵌套模块是否正确

node.js - 当前的 URL 字符串解析器已弃用