navi
navi

Reputation: 1

Rego: how to merge objects set values

How can I merge the values of an object in rego (set type) into a single set containing all the object values ? This is my input object :

input_data = {
  "1": {
    "bob": {"a", "b", "c"},
    "kim": {"c", "e", "f"}
  },
  "2": {
    "may": {"x", "k"},
    "kim": {"y"}
  }
}

And this is the output I want:

output = {
  "1": {"a", "b", "c", "e", "f" },
  "2": {"x", "k", "y"}
}

How can I achieve this in rego ?

I tried the code below but it results in an error eval_conflict_error: object keys must be unique

merge_sets(input_data) := { keys: vals |
  some key, vals
  input_data[keys][_][vals]
}

Upvotes: 0

Views: 853

Answers (2)

Charlie Egan
Charlie Egan

Reputation: 5203

Edit Johan's answer below should be the accepted answer now. https://stackoverflow.com/a/77148529/1510063

You could do that like this using comprehensions:

package play

import future.keywords.in

source_data := {
    "1": {
        "bob": {"a", "b", "c"},
        "kim": {"c", "e", "f"},
    },
    "2": {
        "may": {"x", "k"},
        "kim": {"y"},
    },
}

output := {k: v |
    some k, d in source_data

    v := {e |
        some user, set in d
        some e in set
    }
}

See here: https://play.openpolicyagent.org/p/qZifwGy6bW

Upvotes: 2

Johan Fylling
Johan Fylling

Reputation: 118

In an upcoming release (hopefully 0.57.0), OPA will support multiple variables in the ref of a rule, which'll allow you to achieve the same with:

package example

import future.keywords

input_data = {
  "1": {
    "bob": {"a", "b", "c"},
    "kim": {"c", "e", "f"}
  },
  "2": {
    "may": {"x", "k"},
    "kim": {"y"}
  }
}

output[k] contains v {
    some v in input_data[k][_]
}

Upvotes: 2

Related Questions