【问题标题】:How to insert a LUA Table to Tarantool with Key and Value?如何使用键和值将 LUA 表插入 Tarantool?
【发布时间】:2020-09-16 19:34:17
【问题描述】:

我有一个 JSON 字符串:

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

我已经使用 Tarantool 的模块 json 将其转换为 Lua Table:

table = json.decode(JSONstring)

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

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

当我选择以 JSON 形式添加到 Tarantool 数据库的表时,结果是这样的:

Cannot access values through key

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

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

非常感谢您的帮助!!!

【问题讨论】:

    标签: json lua lua-table tarantool


    【解决方案1】:

    你基本上是在空间中插入一个包装元组,而不是 table 对象本身,所以当你这样做时:

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

    你得到你的元组,而不是table。也就是说,如果您想使用键访问 table 的字段,您只需要像这样索引该 obj:

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

    一旦您习惯了它,请查看 tarantool space 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 及其 flatten/unflatten 方法。 README中有例子

    【讨论】:

    • 非常感谢您的详细回答,它对我有很大帮助。祝你有美好的一天!
    • 为了完整起见,还值得一提JSON path indices
    猜你喜欢
    • 1970-01-01
    • 2017-07-18
    • 2018-09-30
    • 2014-05-01
    • 2020-10-07
    • 2017-05-15
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    相关资源
    最近更新 更多