How to union fields to get distinct count?

data:

[
{"from_uid": 1, "to_uid": 2},
{"from_uid": 2, "to_uid": 1},
{"from_uid": 2, "to_uid": 3}
]

I want to query the result like following sql:

select count(distinct a.uid) from (
  select from_uid as uid from data group by from_uid
  union
  select to_uid as uid from data group by to_uid
) a

I tried cardinality query but it can only query one field.

Could you use a script and return a list of both values? I haven't tried it but I expect you could do it.

A script would work, but if you need to run such queries regularly, the best option would be to have a field that contains both values so that aggregations can leverage ordinals (which are only built per field).