有没有办法在将数组存储在Tarantool中的字段上建立索引?

问题描述

我需要从两个部分创建局部索引,其中第一个字段是整数,第二个字段是数组。

然后,我需要选择所有第一个键的元组的值都相等且第二个键的值包含在数组中的元组

Box.space.test:select()
[...,1,[1,2,3]]
[...,[3,4,5]]
[...,7,9]]

Box.space.test.index.test:select({1,3})
[...,5]]

可以使用Tarantool完成吗?

解决方法

是的,这是可能的。您可以在任何索引中使用数组索引部分。 box.space.create_index()上的文档对此进行了描述。这不是很明显,您需要在页面上搜索“ [*]”。

这是您可以使用的完整示例:

local yaml = require('yaml')

box.cfg({listen=3301})

box.schema.space.create('test',{if_not_exists=true})
box.space.test:format({
      {name='id',type='unsigned'},{name='value',{name='items',type='array'}})

box.space.test:create_index('primary',{
                               unique = true,parts = { {field = 'id',type = 'unsigned'}},if_not_exists=true})


-- items[*] define a multi-key index part
box.space.test:create_index('secondary',{
                               unique = false,parts = {
                                  {field = 'value',type = 'unsigned'},{field='items[*]',type='unsigned'}},if_not_exists=true})

box.space.test:put({1,1,{1,2,3}})
box.space.test:put({2,{2,7,8}})
box.space.test:put({3,{3,8}})
box.space.test:put({4,{4,5,6}})

local result = box.space.test.index.secondary:select({1,2})
print(yaml.encode(result))

此代码将输出以下内容:

---
- [1,[1,3]]
- [2,[2,8]]
...