Skip to content

Grouping Serialization

Convert grouping specifications to/from compact string format for URLs and APIs.

Format

Tuple format: ("field1,field2", "agg1:func,agg2:func:field")

  • Grouping fields: comma-separated list
  • COUNT aggregation: id:count (field omitted)
  • Other aggregations: id:function:field (field required)

Usage

from therismos.grouping import GroupSpec, Aggregation, AggregationFunction, Serializer

serializer = Serializer()

spec = GroupSpec(
    group_by=["category", "region"],
    aggregations=[
        Aggregation("total", AggregationFunction.COUNT),
        Aggregation("min_price", AggregationFunction.MIN, "price"),
        Aggregation("avg_price", AggregationFunction.AVERAGE, "price"),
    ],
)

text = serializer.serialize(spec)
# ("category,region", "total:count,min_price:min:price,avg_price:average:price")

restored = serializer.deserialize('("category,region", "total:count,min_price:min:price")')

Roundtrip

original = GroupSpec(
    group_by=["category", "region"],
    aggregations=[
        Aggregation("total", AggregationFunction.COUNT),
        Aggregation("avg_price", AggregationFunction.AVERAGE, "price"),
    ],
)

serializer = Serializer()
text = serializer.serialize(original)
restored = serializer.deserialize(text)

assert restored.group_by == original.group_by
assert len(restored.aggregations) == len(original.aggregations)