A little toolkit for multiset (bag) basic operations, storing bags into JSONb objects.
Two flavors: schema lib implementation and direct implementation (schema public).
As a restric jsonb-schema, with only key-value pairs and value as integer, the datatype is named jbags.
bag.valid(JSONb)retboolean:
Validate internal representation as bag (key-multiplicity pairs).bag.sc(JSONb)retbigint:
Scalar cardinality of the bag.bag.contains(JSONb, text)retboolean:
Checks whether the element is present (at least once) in the bag.bag.j_as_t(JSONb[])retSETOF bag.ref:
Returns an array of JSONb-bag representations as an element-multiplicity table.bag.j_as_t(JSONb)retSETOF bag.ref:
Similar.bag.scaled_by(JSONb,int)retJSONb:
Scalar multiplication. $2⊗$1.bag.intersection(JSONb[])retJSONb:
...bag.union(JSONb[])retJSONb:
...bag.sum(JSONb[])retJSONb:
...bag.is_sub(JSONb, JSONb[])retboolean:
Checks $1 ⊑ ($2[1] ∩ $2[2] ∩...), that is if $1=($1 ∩ $2[1] ∩ $2[2] ∩...).bag.intersection(JSONb,JSONb)retJSONb:
$1 ∩ $2.bag.is_sub(JSONb, JSONb)retboolean:
Checks $1 ⊑ $2, whether each element in the bag1 occurs in bag1 no more often than it occurs in the bag2.bag.union(JSONb,JSONb,boolean DEFAULT true)retJSONb:
... Trying to optimize the union (or sum) of two bags.bag.j_as_t(JSONb)retSETOF bag.ref:
See bag_as_schema.sql source code.
Same as bag.*() but in the public catalog of functions with jbag datatype as parameter.
NOTE: j_as_t() renamed to astable().
See bag.sql source code.