在lua脚本中改变地图类型的aerospike db记录中bin的值

时间:2018-01-22 10:21:13

标签: lua user-defined-functions lua-table aerospike

说空气动力学数据库记录了如下数据

让命名空间为员工

name age characteristics  
sachin 25 MAP('{"weight":70, "height":25}')  

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

我试过更改普通数据类型的bin,如下所示,i,e i 试图改变年龄如下:

function changeAgeOfEmployee(rec)
  if not aerospike:exists(rec) then
     error ("Invalid Record. Returning")
     return
  else
     age = 30
     rec['age'] = age
     aerospike:update(rec)
  end
end

但我不知道如何更改lua中地图中的值,有人可以帮助我吗

2 个答案:

答案 0 :(得分:2)

您的MAP数据类型基本上是一个lua表。 lua中的MAP可以写成:

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

要遍历所有键/值对,您应该使用pairs iterator,如下所示:

for key, value in map.pairs(m) do
    m[key] = 30 --this changes all the values of your MAP to 30
end

答案 1 :(得分:2)

如果您要修改地图的某个键或列表的索引,则应将该bin转换为局部变量,然后在更新之前将其设置回记录。

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

在AQL中

$ aql
Aerospike Query Client
Version 3.15.1.2
C Client Version 4.3.0
Copyright 2012-2017 Aerospike. All rights reserved.
aql> register module './test.lua'
OK, 1 module added.
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 row in set (0.002 secs)

aql> execute test.changes() on test.demo where PK='88'
+---------+
| changes |
+---------+
|         |
+---------+
1 row in set (0.001 secs)

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 row in set (0.000 secs)