【问题标题】:Select from tarantool using multiple conditions使用多个条件从 tarantool 中选择
【发布时间】:2021-01-01 06:11:18
【问题描述】:

如何一次从一个空格中选择包含两个或多个字段的条件? 我在文档中没有找到示例。

【问题讨论】:

    标签: nosql tarantool


    【解决方案1】:

    有两种方法可以做到这一点:使用 SQL 或使用较低级别的 lua API。

    第一个要求您设置空格格式(请参阅here)。它看起来像这样:

    box.space.myusers:format({{name='id',type='number'},
                              {name='first_name',type='string'},
                              {name='last_name',type='string'}})
    

    这是 SQL 计算列名所必需的。然后就可以这样查询了:

    box.execute([[SELECT "id" FROM "myusers" WHERE "first_name"='John' AND "last_name"='Doe';]])
    

    从同一空间中选择的另一种方法是:

    user_ids = {}
    for_,user in box.space.myusers.index.first_name:pairs("John") do
        if user.last_name == "Doe" then
            table.insert(user_ids, user.id)
        end
    end
    

    查看here 了解有关低级空间 API 的更多详细信息。

    【讨论】:

      【解决方案2】:

      或者,您可以编写自定义“过滤器”函数,而不是在“if”下编写附加条件。并按以下方式使用:

      例如,您有以下架构:

      space = box.schema.space.create('test')
      space:create_index('primary')
      space:replace{1, 'Odd'}
      space:replace{2, 'Even'}
      space:replace{3, 'Odd'}
      
      -- Print
      -- [1, 'Odd']
      -- [2, 'Even']
      -- [3, 'Odd']
      --
      for _, tuple in space:pairs() do
          print(tuple)
      end
      
      -- If you want to select tuples with second "Odd" field
      -- define
      function is_odd(tuple)
          return tuple[2] == 'Odd' -- could be more complex condition
      end
      
      -- And then
      -- it will print
      -- [1, 'Odd']
      -- [3, 'Odd']
      --
      for _, tuple in space:pairs():filter(is_odd) do
          print(tuple)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-29
        • 2023-03-22
        • 2013-04-25
        • 2011-03-20
        相关资源
        最近更新 更多