【问题标题】:Use Boost multi_index for combined keys使用 Boost multi_index 组合键
【发布时间】:2019-09-28 00:33:59
【问题描述】:

如何使用 Boost multi_index 将三个键组合成一个查询表达式?考虑以下索引结构:

struct indexItems {
    uint64_t x; // assume non-unique index
    std::string y; // assume unique within x
    std::string z; // assume unique within y
};

假设我想使用二元 AND 运算符查询项目:x=1 AND y="a" AND z="s"。我该怎么做?

所有查询和插入都将使用 x+y+z 的组合从 multi_index 中插入、更新和删除项目。除此之外,我需要遍历按 x 排序的 y 和 z。

到目前为止,我发现的示例仅处理单个索引。

【问题讨论】:

  • 您的所有查询是否都处理 x+y+z 或者您是否也在寻找任意组合,例如 x+z 和 y+z 查询?
  • 好问题。我会更新说明。
  • 当您说“我需要遍历按 x 排序的 y 和 z”时,这是否意味着您需要获取具有特定 y 的所有值,然后按 x 的顺序遍历这些值?或者这是否意味着您要遍历所有按 x 排序的值?
  • 后者。我从不需要查询特定的 y 或 z,而是遍历 x 以及该 x 的所有关联 y 和 z。

标签: c++ boost c++14


【解决方案1】:

您实际上不需要 multi_index_container 。你可以这样做:

inline bool operator<(const indexItems& l, const indexItems& r) {
    return std::tie(l.x, l.y, l.z) < std::tie(r.x, r.y, r.z);
}

inline bool operator==(const indexItems& l, const indexItems& r) {
    return std::tie(l.x, l.y, l.z) == std::tie(r.x, r.y, r.z);
}

std::set<indexItems> items; // or use map with any second type

现在您有一组数据,首先按 x,然后按 y,然后按 z。查询x=1 AND y="a" AND z="s":

items.find(indexItems{1, "a", "s"});

遍历所有按 x 排序的值(其次按 y 和 z 排序,虽然这实际上不是必需的,但也没有什么坏处):

for (const indexItems& item : items)
    // ...

作为奖励,如果您想在x 的某个范围内查找所有值:

auto it = items.lower_bound(indexItems{100});
auto end = items.upper_bound(indexItems{105});
for (; it != end; ++it)
    // ...

【讨论】:

  • 非常优雅。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 2017-01-23
  • 2016-03-23
  • 2011-03-29
  • 1970-01-01
相关资源
最近更新 更多