People tend to think that zset is just a list of passes. This is not true. This is a skip list (ordered data structure) plus a non-ordered dictionary (implemented as a hash table). The semantics of the merge operation must be defined. For example, how would you combine disjoint zsets whose common elements do not have the same rating?
To implement the merge algorithm for ZUNIONSTORE, you will need to arrange the elements (easily using skip lists), combine them when building the output (which is also zset: skiplist plus dictionary).
Since the power of the result cannot be guessed at the beginning of the algorithm, I do not think that it is possible to build this skiplist + dictionary in linear time. At best, it will be O (n log n). Thus, the merger is linear, but the construction of the result is not: it wins in the use of the merge algorithm.
Now, if you want to implement ZUNION (i.e., directly return the result without creating the result as a zset) and limit the result to a given number of elements, the merge algorithm makes sense.
RDBMS supporting merge joins can usually do this (but this is usually not very efficient due to the cost of random I / O). I do not know about NoSQL storage that supports such features.
To implement it in Redis, you can try the Lua server on the server side of the script, but it can be complicated, and I think it will only be effective if zsets are much larger than the limit provided in zunion. In this case, a limit on the number of elements will offset the overhead of executing the interpreted Lua code.
The last opportunity is to implement it in C in the Redis source code, which is not so difficult. The downside is the burden of supporting the patch for the versions of Redis that you are using. Redis itself provides no reason for this, and the idea of ββdefining Redis plugins (derived from Redis source code) is usually rejected by the author.
source share