如何将带有键和值的LUA表格插入Tarantool?

我有一个JSON字符串:

{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
    "geohash64" : 5637765837143565,
    "mime_type" : "image/jpg"
}

然后我使用Tarantool的模块JSON将其转换为Lua表:

table = json.decode(JSONstring)

然后我想将表插入到ID = 1的Tarantool中

box.space.somespace:insert{1, table}

当我选择已添加到Tarantool数据库中的表并以JSON格式返回时,结果如下所示:

无法通过键访问值

我只能访问table[1]和table[2]:table[1]是ID = 1,而table[2]是所有JSON字符串。这意味着我无法通过键值访问JSON的值:table['entry_offset'],table['entry_size'],....尝试访问它们时返回nil

那么我该如何将Lua表插入到Tarantool中,然后通过其键访问值?

非常感谢您的帮助!

点赞
用户1881632
用户1881632

你基本上是把一个包装元组插入空间,而不是直接插入table对象本身,所以当你执行以下代码时:

obj = box.space.somespace:get{1}

你会得到一个元组而不是table。也就是说,如果你想使用键来访问table的字段,你只需要这样编制索引:

table = obj[2]
print(table.entry_offset)

一旦你习惯了这种方式,就可以查看tarantool的[空间格式] (https://www.tarantool.io/en/doc/2.3/reference/reference_lua/box_space/#lua-function.space_object.format)功能,以及它的`tomap`/ frommap函数。以下是一个基本示例,可能对你有帮助:

box.cfg {}
box.schema.create_space('test', {if_not_exists = true})
box.space.test:create_index('pk', {unique = true, if_not_exists = true, parts = {1, 'unsigned'}})
box.space.test:format({
    { name = 'id', 'unsigned' },
    { name = 'entry_offset', 'unsigned' },
    { name = 'entry_size', 'unsigned' },
    { name = 'created_time', 'unsigned' },
    { name = 'additional_meta', 'map' },
})

json = require('json')
obj_json = [[{
"entry_offset" : 180587225765,
"entry_size" : 54003,
"created_time" : 1577500878,
"additional_meta" : {
    "geohash64" : 5637765837143565,
    "mime_type" : "image/jpg"
}}]]
obj = json.decode(obj_json)
obj.id = 1

tuple = box.space.test:frommap(obj)
box.space.test:insert(tuple)
result = box.space.test:get({1}):tomap()

print(result.additional_meta.mime_type)

或者,对于更高级的序列化方法,请查看[avro-schema] (https://github.com/tarantool/avro-schema)以及它的`flatten`/ unflatten方法。阅读[README] (https://github.com/tarantool/avro-schema#generated-routines)中的示例。

2020-05-29 10:19:11