Achieve high-performance multidimensional data pivoting with HyperLogLog

Updated at:
Copy as MD

HyperLogLog (HLL) is a probabilistic data structure that estimates cardinality—the count of distinct values in a large dataset—with a small, fixed memory footprint. In e-commerce analytics, this trade-off matters: computing exact COUNT DISTINCT across hundreds of millions of rows and multiple tag dimensions can take minutes per query, whereas querying pre-aggregated HLL sketches returns results in milliseconds regardless of data volume.

This topic walks through a complete precomputation workflow: designing the schema, writing the precomputation SQL with GROUPING SETS, querying across dimensions using array and HLL operations, and scheduling day-level and month-level rollups.

For a primer on HLL functions, see Use HyperLogLog.

Best practices

The following best practices summarize the architectural approaches described in this topic:

  • AnalyticDB for PostgreSQL precomputes data based on query requests. With the precomputation results, you only need to specify the filter criteria for a data view query and AnalyticDB for PostgreSQL responds to your query for data in all dimensions within 100 milliseconds.

  • AnalyticDB for PostgreSQL executes a GROUPING SETS statement to collect data statistics in multiple dimensions simultaneously. This reduces repetitive data scanning and computing workloads and increases processing efficiency.

  • AnalyticDB for PostgreSQL records user IDs in each dimension as an array. This enables you to not only view data but also identify specific users.

  • AnalyticDB for PostgreSQL uses hll fields to store estimated data statistics for complex views. For example, the values of multiple hll fields can be united to analyze unique visitors (UVs) and identify new UVs.

  • AnalyticDB for PostgreSQL implements stream processing using PipelineDB to compute data and obtain statistics in real time.

  • AnalyticDB for PostgreSQL stores intermediate data (also referred to as raw data) in the OSS_FDW external table and uploads the table to Alibaba Cloud Object Storage Service (OSS). This way, AnalyticDB for PostgreSQL does not need to store intermediate data but only uses it for precomputation, reducing write volume and storage footprint.

  • AnalyticDB for PostgreSQL uses level-1 and level-2 partitions of Greenplum to break a data view query into smaller units. It uses indexed tags to further narrow down the scope of searches. By doing so, AnalyticDB for PostgreSQL responds to your query for data in any dimension and among any volume within 100 milliseconds.

  • AnalyticDB for PostgreSQL uses column-oriented storage to increase the data compression ratio and reduce the storage space occupied by data statistics.

Background

A typical e-commerce analytics schema tracks brand IDs, sales territory IDs, user IDs, and timestamps. Each user carries multiple tags—gender, age, hobby, and so on—that analysts use to slice and compare cohorts across dimensions.

A common query pattern: "For brand X, in territory Y, on day Z, how many users have tag A?" Running this as a multi-table join every time is expensive. A better approach is to precompute the results once, store them in a compact format, and serve all dimension combinations from that precomputed table.

Data structures

The example uses three source tables:

t1 — active users per sales territory per day

t1 (
  uid,       -- User ID
  groupid,   -- Sales territory (channel) ID
  day        -- Date
)

t2 — brand membership

t2 (
  uid,    -- User ID
  brand   -- Brand ID
)

t3 — user tags

t3 (
  uid,    -- User ID
  tag1,   -- Tag 1, e.g., hobby
  tag2,   -- Tag 2, e.g., gender
  tag3,   -- Tag 3, e.g., age group
  ...
)

Without precomputation, a typical dimension query joins all three tables:

SELECT
  'hobby' AS tag,
  t3.tag1 AS tag_value,
  count(1) AS cnt
FROM t1, t2, t3
WHERE
  t1.uid = t3.uid
  AND t1.uid = t2.uid
  AND t2.brand = ?
  AND t1.groupid = ?
  AND t1.day = '2017-06-25'
GROUP BY t3.tag1;

This scan is expensive, and you need a separate query for each tag dimension. Precomputation eliminates both problems.

Schema design for precomputation

Design the precomputed result table to support sub-100ms queries:

  • Columnar storage: reduces I/O for aggregation queries

  • Partition by day, then by brand and groupid: lets the query engine skip irrelevant partitions

  • Random distribution: spreads data evenly across compute nodes

  • One index per tag field: narrows down the row scan within a partition

t_result (
  day,       -- Date
  brand,     -- Brand ID
  groupid,   -- Sales territory (channel) ID
  tag1,      -- Tag 1
  tag2,      -- Tag 2
  tag3,      -- Tag 3
  ...        -- Tag n
  cnt,       -- User count
  uids,      -- User ID array (optional; omit if individual IDs are not needed)
  hll_uids   -- HLL sketch of user IDs
)

With this structure, a dimension query becomes a simple filter:

SELECT day, brand, groupid, 'tag?' AS tag, cnt, uids, hll_uids
FROM t_result
WHERE
  day = ?
  AND brand = ?
  AND groupid = ?
  AND tag? = ?;

AnalyticDB for PostgreSQL filters on the first three partition columns, then applies the tag index—returning results within 100 milliseconds for any data volume.

Precompute data with GROUPING SETS

A single GROUPING SETS statement precomputes statistics across all tag dimensions in one pass. This avoids running a separate query for each tag:

INSERT INTO t_result
SELECT
  t1.day,
  t2.brand,
  t1.groupid,
  t3.tag1,
  t3.tag2,
  t3.tag3,
  ...
  count(1) AS cnt,
  array_agg(uid) AS uids,                          -- Aggregate user IDs into an array
  hll_add_agg(hll_hash_integer(uid)) AS hll_uids   -- Build an HLL sketch from user IDs
FROM t1, t2, t3
WHERE
  t1.uid = t3.uid
  AND t1.uid = t2.uid
GROUP BY
  t1.day,
  t2.brand,
  t1.groupid,
  GROUPING SETS (
    (t3.tag1),
    (t3.tag2),
    (t3.tag3),
    (...),
    (t3.tagn)
  );

GROUPING SETS scans the source data once and generates a separate group for each tag value listed. The result is one row per (day, brand, groupid, tag_value) combination, covering all dimensions simultaneously.

Query across dimensions

Array-based operations

When you need the exact set of user IDs, use these helper functions:

Difference — users in one set but not the other:

CREATE OR REPLACE FUNCTION arr_miner(anyarray, anyarray) RETURNS anyarray AS $$
  SELECT array(SELECT * FROM (SELECT unnest($1) EXCEPT SELECT unnest($2)) t GROUP BY 1);
$$ LANGUAGE sql STRICT;

Intersection — users in both sets:

CREATE OR REPLACE FUNCTION arr_overlap(anyarray, anyarray) RETURNS anyarray AS $$
  SELECT array(SELECT * FROM (SELECT unnest($1) INTERSECT SELECT unnest($2)) t GROUP BY 1);
$$ LANGUAGE sql STRICT;

Union — all users across both sets (deduplicated):

CREATE OR REPLACE FUNCTION arr_merge(anyarray, anyarray) RETURNS anyarray AS $$
  SELECT array(SELECT unnest(array_cat($1, $2)) GROUP BY 1);
$$ LANGUAGE sql STRICT;

Example: To identify new users who appeared during a promotion that started on June 25, 2017 and were not active the day before:

arr_miner(uid2[], uid1[])
-- uid1[]: user IDs as of June 24, 2017
-- uid2[]: user IDs from June 25, 2017 onward

HLL-based operations

When you need estimated counts rather than exact ID sets, HLL operations are orders of magnitude faster.

Count distinct values in a single HLL field:

hll_cardinality(hll_uids)

Combine two HLL fields to obtain a unique value:

hll_union()

Example: To estimate the number of new users attracted by the same promotion:

hll_cardinality(uid2_hll) - hll_cardinality(uid1_hll)
-- uid1_hll: HLL sketch as of June 24, 2017
-- uid2_hll: HLL sketch from June 25, 2017 onward
HyperLogLog estimates cardinality with a small approximation error. For most analytics use cases—unique visitors (UVs), cohort sizing, trend analysis—this accuracy is sufficient. Use array-based operations when exact user IDs are required.

Schedule precomputation

Day-level precomputation

Run the INSERT INTO t_result ... GROUP BY ... GROUPING SETS statement above once per day to append the day's statistics. Historical data stays unchanged.

Month-level rollup

To query monthly statistics without re-scanning raw data, roll up the daily rows using hll_union_agg for HLL fields and a custom array aggregate for ID arrays.

First, define an aggregate function that merges arrays:

CREATE AGGREGATE arragg (anyarray) (sfunc = arr_merge, stype = anyarray);

Verify the function:

SELECT arragg(c1) FROM (VALUES (ARRAY[1,2,3]), (ARRAY[2,5,6])) t (c1);
   arragg
-----------
 {6,3,2,1,5}
(1 row)

Then aggregate daily rows into a month-level summary table:

INSERT INTO t_result_month
SELECT
  to_char(day, 'yyyy-mm') AS month,
  brand,
  groupid,
  tag1,
  tag2,
  tag3,
  ...
  array_length(arragg(uid), 1) AS cnt,
  arragg(uid) AS uids,
  hll_union_agg() AS hll_uids   -- Merges HLL sketches across days
FROM t_result
GROUP BY
  to_char(day, 'yyyy-mm'),
  brand,
  groupid,
  tag1,
  tag2,
  tag3,
  ...;

The month-level table has the same schema as t_result, with month (in yyyy-mm format) replacing day. Apply the same pattern to build year-level rollups from month-level data.

Stream processing

For high-throughput data pipelines, use PipelineDB to compute real-time statistics and write the output to AnalyticDB for PostgreSQL. When data volume is large, distribute inbound data across stream processing nodes using a partition key, then merge the per-node results into the target table.

For intermediate data that does not need persistent storage in AnalyticDB for PostgreSQL, store it in an OSS_FDW external table backed by Object Storage Service (OSS). This reduces write volume and storage footprint while still making the data available for precomputation.

Related topics