Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

opa - Open Policy Agent - Improve performance of a grouping comprehension

I have a id and role mapping in below format

{
    "ra": [
      {
        "id": 168,
        "code": "AFAP"
      },
      {
        "id": 180,
        "code": "ABC"
      },
      {
        "id": 180,
        "code": "ABCMND"
      }
   ]
}

I need the output to be like below

{
    "roleactions": {
        "168": [
            "AFAP"
        ],
        "180": [
            "ABC",
            "ABCMND",
            "DCRMP"
        ]
    }
}

So i wrote the below code

roleactions = r_map {
    r := data.ra
    r_map := {id: list |
        some i
        id := r[i].id
        list := [obj |
            some j
            r[j].id == id
            obj := r[j].code
        ]
    }
}

But when I run this for it almost takes 5-6 seconds

Performance

Found 1 result in 5682526.465 μs.

Can someone guide on how to make write this policy map to improve performance?

question from:https://stackoverflow.com/questions/66052212/open-policy-agent-improve-performance-of-a-grouping-comprehension

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OPA can evaluate comprehensions like this in linear-time: https://www.openpolicyagent.org/docs/latest/policy-performance/#comprehension-indexing. The problem in this case is that the local variable r is not safe when considering the comprehensions in isolation.

If you refactor the comprehension like below, the runtime should be linear:


roleactions := r_map {
    r_map := {id: list |
        some i
        id := data.ra[i].id
        list := [obj |
            some j
            data.ra[j].id == id
            obj := data.ra[j].code
        ]
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...