在 Lua 脚本中更改 Aerospike 数据库中映射类型记录中 bin 的值

假设 Aerospike 数据库拥有以下记录数据

假设命名空间为 employee

名称 年龄 特征
sachin 25 MAP('{"weight":70, "height":25}')

现在我想通过 Lua 脚本更改所有 employee 命名空间中的记录中 map 中高度的值。

我已经尝试过更改普通数据类型中 bins 的方法,例如更改年龄,如下所示:

function changeAgeOfEmployee(rec)
  if not aerospike:exists(rec) then
     error ("无效记录。返回")
     return
  else
     age = 30
     rec['age'] = age
     aerospike:update(rec)
  end
end

但我不知道如何在 Lua 中更改 map 中的值,有人可以给我提供帮助吗?

点赞
用户7253993
用户7253993

你的 MAP 数据类型基本上就是一个 Lua 表格。在 Lua 中,可以写成:

local m = map {"weight" => 70, "height" => 25}

要循环遍历所有的键/值对,可以使用 pairs 迭代器,就像这样:

for key, value in map.pairs(m) do
    m[key] = 30 --这会将你的 MAP 的所有值都更改为 30
end
2018-01-22 10:41:57
用户582436
用户582436

如果要修改一个映射的键或列表的索引,应该将该 bin 强制转换为一个本地变量,然后在更新之前将其设置回记录。

function changes(rec)
  rec['i'] = 99
  local m = rec['m']
  m['a'] = 66
  rec['m'] = m
  aerospike:update(rec)
end

在AQL中:

$ aql
Aerospike 查询客户端
版本 3.15.1.2
C 客户端版本 4.3.0
版权所有 2012-2017 Aerospike。保留所有权利。
aql> register module './test.lua'
OK,已添加 1 个模块。
aql> select * from test.demo where PK='88'
+----+-------+--------------------------------------+------------------------------------------+
| i  | s     | m                                    | l                                        |
+----+-------+--------------------------------------+------------------------------------------+
| 88 | "xyz" | MAP('{"a":2, "b":4, "c":8, "d":16}') | LIST('[2, 4, 8, 16, 32, NIL, 128, 256]') |
+----+-------+--------------------------------------+------------------------------------------+
1 行(用时 0.002 秒)

aql> execute test.changes() on test.demo where PK='88'
+---------+
| changes |
+---------+
|         |
+---------+
1 行(用时 0.001 秒)

aql> select * from test.demo where PK='88'
+----+-------+---------------------------------------+------------------------------------------+
| i  | s     | m                                     | l                                        |
+----+-------+---------------------------------------+------------------------------------------+
| 99 | "xyz" | MAP('{"a":66, "b":4, "c":8, "d":16}') | LIST('[2, 4, 8, 16, 32, NIL, 128, 256]') |
+----+-------+---------------------------------------+------------------------------------------+
1 行(用时 0.000 秒)
2018-01-23 21:08:26