【问题标题】:Does Rego Set lookup will iterate all items in the set?Rego Set 查找是否会迭代集合中的所有项目?
【发布时间】:2021-06-15 16:19:43
【问题描述】:
package example

default allow = false

input = {
    "value_2": {"c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "a", "a"},
    "value_1": ["c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "b", "c", "a", "a"]
}

allow {
    input.value_1[_] == "a"
    input.value_2["a"] == "a"
}

按照示例,哪一个会更快地进行查找?

【问题讨论】:

    标签: open-policy-agent rego


    【解决方案1】:

    设置查找是常数时间:

    a_set["a"]  # <-- this is constant time
    

    集合元素的迭代和比较没有(当前)优化并且是线性时间的:

    a_set[_] == "a" # <-- this is linear-time
    

    虽然上面的例子是无效的,因为input.value_2 被定义为一个array(不是一个set)所以input.value_2["a"] 是无效的。如果您尝试此示例,您将收到来自编译器的类型错误:

    1 error occurred: policy.rego:12: rego_type_error: undefined ref: data.example.input.value_2.a
        data.example.input.value_2.a
                                   ^
                                   have: "a"
                                   want (type): number
    

    假设您最初想使用 set,只需使用查找语法 (s[k]) 并且不要费心进行额外的相等性检查(除非您正在测试 false 是否为包含在集合中,但这很奇怪。)

    请注意,OPA 网站上的 Policy Reference 页面解释了如何对数组、对象和集合执行查找、比较和迭代。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2017-02-11
      • 1970-01-01
      • 2013-07-13
      • 2018-06-05
      • 1970-01-01
      • 2016-01-27
      相关资源
      最近更新 更多