0
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"
}

follow the example, which one will do the lookup faster?

1 Answers1

0

Set lookup is constant time:

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

Iteration and comparison of set elements is not (currently) optimized and is linear-time:

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

The example above though is not valid because input.value_2 is defined as an array (not a set) so input.value_2["a"] is invalid. If you try this example you'll receive a type error from the compiler:

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

Assuming you wanted to use a set originally, just use the lookup syntax (s[k]) and do not bother with the additional equality check (unless you're testing for whether false is contained in the set, but that would be odd.)

Note, the Policy Reference page on the OPA website explains how to perform lookups, comparison, and iteration on arrays, objects, and sets.

tsandall
  • 1,544
  • 8
  • 8