The previous post explained how BSI represents numbers, how NumericIndexedVector operations work, and how to use its ClickHouse interfaces. This post applies the representation to real workloads: designing bucketing and position encoding, deciding which queries suit a migration, and rewriting SQL and adapting the ingestion pipeline. It closes with the paper’s measurements and explains where the gains come from.

These recommendations come from large-scale metric computation at WeChat: roughly 100,000 production metrics, permanently retained data, and hundreds of ClickHouse nodes serving hot data. The performance figures come from Xiong and Wang’s paper; Section 4 gives the full comparison.

1. Bucketing and Position Encoding

Bucketing determines how data is distributed for processing; position encoding determines how keys are represented within each bucket. Bucketing assigns vectors to different nodes and also supports variance estimation for experiment metrics. Position encoding maps keys within a bucket to compact positions, reducing the bitmap’s position range. We start with 32-bit keys, then apply the same approach to 64-bit business keys.

1.1 Bucketing: Sharding and Variance Estimation

Bucketing splits a large vector into smaller vectors that can be processed separately. Different buckets can be assigned to different ClickHouse shards, allowing construction and queries to run in parallel.

Bucketing also helps estimate metric variance in A/B experiments. If randomization units are independent and assigned to buckets with an appropriate random scheme, bucket-level aggregates can estimate variance without rescanning raw records. See Covariance Estimation and its Application in Large-Scale Online Controlled Experiments.

For UInt32 keys, a common scheme applies MurmurHash32 and buckets by the high hash bits:

  1. Compute the hash with MurmurHash32. For the 32-bit input case here, it maps business keys one-to-one to 32-bit hash values, making their distribution more uniform.
  2. Use the high 10 bits as bucket_id, giving 1024 buckets. The bucket ID only determines the shard and vector to which a record belongs.
  3. Pass the full 32-bit hash when constructing the vector. Hashes within one bucket lie in [bucket_id × 2^{22}, (bucket_id+1) × 2^{22}), a consecutive range of about 4 million positions. A bucket typically contains tens to hundreds of thousands of actual keys; position encoding further reduces the range they occupy.
-- MurmurHash32 + top 10 bits as bucket id (UInt32 key)
SELECT
  dt,
  bitShiftRight(murmurHash3_32(key), 22) AS bucket_id,
  groupNumericIndexedVectorState(murmurHash3_32(key), val) AS v_state    -- in-vector key is the full hash
FROM source_table
GROUP BY dt, bucket_id;

Bucketing, hashing, and consecutive high-bit ranges solve different problems. The following approaches increase costs or violate the conditions for random bucketing:

  • Constructing one vector for all keys prevents distribution across shards and increases the cost of constructing and querying that vector.
  • Bucketing directly by the high bits of business keys can produce uneven loads when user IDs cluster in certain ranges or order IDs increase with time. It also fails to satisfy the random-bucketing conditions above.
  • Bucketing by hash modulo while retaining the full hash as the index scatters each bucket’s keys across the entire 32-bit space. RoaringBitmap must maintain more containers with only a few keys, increasing storage and query costs. In practice, the performance gap from high-bit bucketing can reach an order of magnitude and cause query timeouts in severe cases.

1.2 Position Encoding: Consecutive Positions within Each Bucket

After high-bit bucketing, each bucket’s hash range covers about 4 million positions, but it contains only tens to hundreds of thousands of actual keys. Limiting the range does not remove the gaps between keys. Position encoding narrows that range further.

Position encoding maintains a key-to-position dictionary for each bucket. The first new key gets position 0, the second gets 1, and so on; repeated keys return their existing position. BSI bitmaps are then constructed from these positions. Section 3.4 of the paper describes this method.

ClickHouse’s NumericIndexedVector does not build the dictionary automatically. The supplied index is the position used by the bitmap, so the application must perform the encoding during ingestion. Section 1.3 gives the basic dictionary logic.

The immediate benefit is a smaller bitmap position range. Encoded keys occupy a consecutive range starting at zero, reducing the number of containers RoaringBitmap needs to maintain.

Each BSI bitmap records only positions whose corresponding binary bit is 1. The distribution of those positions determines its container types:

Position distribution within a containerContainer typeContainer cost
Many consecutive rangesRun: stores (start, length)Only tens of bytes when there are few ranges
Sparse, at most 4096 elementsArray: sorted array, 2 bytes per element≤8\leq 8 KiB
Dense, more than 4096 elementsBitmap: plain bitmapFixed 8 KiB

For example, encoding a few widely separated business IDs as 0, 1, 2 lets a single small-range container hold them. Position encoding makes the overall position range consecutive, but does not guarantee consecutive 1s at every binary bit. It therefore does not guarantee that every bitmap uses a Run container.

When two vectors use the same dictionary, the same position identifies the same business key. Pointwise operations can then align positions directly, without matching keys row by row.

Thus, vectors that are merged or used together in pointwise operations must share the same encoding. If position 0 means user A in one vector and user B in another, direct computation mismatches them. Vectors built with different dictionaries must first be converted to a consistent encoding.

1.3 Supporting 64-Bit Business Keys with Position Encoding

Business keys such as Snowflake IDs, global user IDs, and hash fingerprints are often 64-bit. The business key’s width can differ from the vector’s internal position width: use the 64-bit key to determine a bucket, then encode it as a 32-bit position within that bucket. The approach remains hashing, bucketing, and position encoding:

Compute murmurHash3_64(key64) and take the remainder modulo 1024 to get bucket_id. Maintain an encoding dictionary and the next available position for each bucket: existing keys return their original encoding, and new keys receive the next consecutive position. This pseudocode shows the dictionary logic:

# Each bucket_id keeps its own encoding dictionary + current max position
encoding: Dict[bucket_id, Dict[key, UInt32]] = {}
next_pos: Dict[bucket_id, UInt32] = {}

def encode(bucket_id, key) -> UInt32:
    if key in encoding[bucket_id]:
        return encoding[bucket_id][key]   # already encoded, return existing position
    pos = next_pos[bucket_id]
    encoding[bucket_id][key] = pos        # new key, assign the next contiguous position
    next_pos[bucket_id] = pos + 1
    return pos

NumericIndexedVector still receives 32-bit positions, while the application dictionary stores the original 64-bit keys. This retains the existing interface and 32-bit RoaringBitmap, avoiding the performance cost of using 64-bit bitmaps directly, as explained in Section 6 of the previous post.

Each bucket can theoretically represent 2322^{32} distinct keys. With 1024 buckets, the total encoding space is about 1024×232≈4.4×10121024 \times 2^{32} \approx 4.4 \times 10^{12}; practical capacity also depends on dictionary size, memory, and cluster resources.

-- Conceptual SQL: encode is the Position Encoding logic above (implemented by the application in the write path; not built into NumericIndexedVector)
SELECT
  dt,
  murmurHash3_64(key64) % 1024 AS bucket_id,
  groupNumericIndexedVectorState(
    encode(bucket_id, key64),    -- per-bucket dictionary lookup + auto-increment
    val) AS v_state
FROM raw_64bit_table
GROUP BY dt, bucket_id;

The following table stores vector states by date and bucket:

CREATE TABLE vec_64 (
  dt Date,
  bucket_id UInt32,     -- murmurHash3_64(key64) % 1024
  v_state AggregateFunction(groupNumericIndexedVector, UInt32, UInt64),
  PRIMARY KEY (dt, bucket_id)
);

At query time, merge states by bucket, then align vectors belonging to the same bucket:

The multiplication below uses an inner join and computes only buckets present on both sides. For addition or subtraction that must retain buckets present on just one side, adjust the bucket join and handle the missing side according to the operation’s semantics.

SELECT sum(numericIndexedVectorAllValueSum(
  numericIndexedVectorPointwiseMultiply(a.v, b.v)))
FROM
  (SELECT bucket_id, groupNumericIndexedVectorMergeState(v_state) AS v
   FROM vec_a GROUP BY bucket_id) AS a
INNER JOIN
  (SELECT bucket_id, groupNumericIndexedVectorMergeState(v_state) AS v
   FROM vec_b GROUP BY bucket_id) AS b
ON a.bucket_id = b.bucket_id;

For global aggregation, compute AllValueSum or Cardinality for each bucket, then add the bucket results. Each business key belongs to exactly one bucket, so it is not counted twice across buckets.

ToMap returns a Map(UInt32, value) for each bucket, where the key is the position supplied to the vector. The application restores original keys through a reverse dictionary, (bucket_id, position) → key64. Keep the bucket ID: position 0 in different buckets refers to different business keys.

The 1024 buckets here are an example. Choose the count according to key cardinality, node count, and bucket size.

The 32-bit scheme uses the full hash directly as the index, so high-bit bucketing keeps positions concentrated within each bucket. The 64-bit scheme assigns new positions within buckets, so modulo can determine the bucket ID. The final positions supplied to the bitmap determine its storage distribution; the bucket-ID calculation alone does not.

2. Use Cases

A migration adds vector construction and storage paths and changes materialized views and downstream SQL. Most of the work goes into data organization and query rewrites, so assess the benefits against the workloads below.

2.1 Workloads Suited to Migration

When all three conditions hold, migration is worth evaluating; actual gains still depend on value distributions, operation types, and construction costs:

  1. Queries frequently join or GROUP BY integer keys, with tens to hundreds of millions of distinct keys.
  2. Values are integers or floating-point numbers, or can be converted to integers in a fixed unit. Integer values must fit the supported types; floating-point inputs use the default encoding of 40 integer bits and 24 fractional bits.
  3. Downstream queries mainly perform per-key pointwise arithmetic, conditional filtering, sums, or key counts.

2.2 Workloads Not Suited to Migration

  • Strings cannot participate directly in BSI numeric operations. Decimal requires exact decimal arithmetic, while a binary step of 2−f2^{-f} cannot represent all decimal fractions exactly. Monetary metrics can first be converted to integer units, for example by multiplying by 100 to represent cents, then used to construct vectors; multiplication, division, and sums still go through Float64, so exact results also require checking the value range.
  • Frequently changing grouping dimensions requires reconstructing vectors indexed by the new key.
  • Window functions, ranking, and time-series computation depend on order; position encoding alone does not provide those semantics.
  • With fewer than a million distinct keys and simple queries, traditional table queries usually have lower absolute latency, and constructing vectors adds overhead.

Floating-point precision: Float32 and Float64 are supported but represented internally as fixed-point values, with 24 binary fractional bits by default. If a workload requires a finer step or exact decimal values, choose suitable integer units first, then check the resulting value range.

2.3 Assessing a Migration

NumericIndexedVector is primarily suited to workloads with tens of millions of distinct integer keys or more, integer or floating-point values, and queries that join by key before computation and aggregation.

3. Usage Guide

The three examples below rewrite per-key arithmetic, joins, and conditional sums as vector operations, followed by a comparison of query-time construction and write-time pre-aggregation. To focus on function composition, they omit bucketing and assume each input table has one row per key. If keys repeat, first confirm the metric’s meaning after aggregation by key before rewriting the query.

3.1 SQL Rewrite: Single-Table Pointwise Arithmetic

Single-table per-key computation applies arithmetic to several columns for the same key, such as val_a * val_b + val_c.

-- row-wise
SELECT key, val_a * val_b + val_c AS combined
FROM T;

Construct one vector for each of the three columns, then multiply and add values at the same key:

WITH
  (SELECT groupNumericIndexedVectorState(key, val_a) FROM T) AS va,
  (SELECT groupNumericIndexedVectorState(key, val_b) FROM T) AS vb,
  (SELECT groupNumericIndexedVectorState(key, val_c) FROM T) AS vc
SELECT numericIndexedVectorToMap(
  numericIndexedVectorPointwiseAdd(
    numericIndexedVectorPointwiseMultiply(va, vb),
    vc));

This SQL returns per-key results through ToMap; use AllValueSum instead if only the total is needed.

Addition operates directly on bitmaps, with little overhead for unused high bits; multiplication decodes, computes, and re-encodes. Single-table workloads typically speed up by several to a dozen times, less than workloads with large joins. Query-time construction still reads the original columns; Section 3.4 explains how pre-aggregation reuses the constructed vectors.

3.2 SQL Rewrite: Key-Based Joins Followed by Computation and Aggregation

Two-table computation first matches A and B by key, then multiplies matching values and sums the products. Rewriting these queries as vector operations can reduce the cost of row-by-row joins.

-- row-wise: hash join + row-wise sum
SELECT sum(A.val_a * B.val_b)
FROM A JOIN B ON A.key = B.key;

Construct a vector on each side, multiply by key, and sum the result:

WITH
  (SELECT groupNumericIndexedVectorState(key, val_a) FROM A) AS va,
  (SELECT groupNumericIndexedVectorState(key, val_b) FROM B) AS vb
SELECT numericIndexedVectorAllValueSum(
  numericIndexedVectorPointwiseMultiply(va, vb));

va and vb use the same index scheme, either original keys or shared position encoding. The same position already identifies the same key, so vector operations need no row-by-row hash join. To return per-key results, replace the outer AllValueSum with ToMap; keys present on only one side appear in the result with a value of zero, so matching the rows of an INNER JOIN also requires filtering by the intersection of both sides’ keys. With bucketed storage, both sides still need alignment by bucket as in Section 1.3.

The more expensive the traditional join, the greater the benefit from avoiding row-by-row matching. In the paper, precomputation CPU use fell to about one quarter. Section 4 gives the full comparison.

3.3 SQL Rewrite: Conditional Sums

A conditional sum includes only qualifying keys, for example summing val_b where val_a < 100.

-- row-wise
SELECT sum(if(val_a < 100, val_b, 0))
FROM T;

First compare to obtain a filter mask, multiply it by the vector to be summed, and then sum the result:

WITH
  (SELECT groupNumericIndexedVectorState(key, val_a) FROM T) AS va,
  (SELECT groupNumericIndexedVectorState(key, val_b) FROM T) AS vb
SELECT numericIndexedVectorAllValueSum(
  numericIndexedVectorPointwiseMultiply(
    numericIndexedVectorPointwiseLess(va, 100),
    vb));

The three functions perform condition evaluation, filtering, and summation in order:

  1. numericIndexedVectorPointwiseLess(va, 100) produces a 0/1 mask, with 1 for qualifying keys.
  2. PointwiseMultiply multiplies the mask by vb, retaining qualifying values and treating the others as zero.
  3. AllValueSum sums the filtered result.

Comparison, mask multiplication, and aggregation combine into a conditional aggregation query. If another vector must be joined, apply the same filtering steps to the multiplication result from Section 3.2.

3.4 Construction Time: Query-Time Construction or Write-Time Pre-Aggregation

Vectors can be constructed during a query or in advance during ingestion. The first approach suits exploratory queries; the second moves construction to ingestion so the results can be reused.

Query-time construction (ad hoc): read the original table and run SELECT groupNumericIndexedVectorState(key, val) FROM T.

This suits queries with manageable key counts, few scanned partitions, or frequently changing grouping dimensions. Each query must read the original columns and construct the vectors; the results are not automatically reused between queries.

Write-time pre-aggregation: create a target table with an AggregateFunction(groupNumericIndexedVector, ...) column, and use a materialized view to store vector states during ingestion.

CREATE MATERIALIZED VIEW mv_vectors TO target_table AS
SELECT
  dt,
  groupNumericIndexedVectorState(key, val_a) AS va_state,
  groupNumericIndexedVectorState(key, val_b) AS vb_state
FROM source_table
GROUP BY dt;

At query time, use groupNumericIndexedVectorMergeState to merge states for the selected dates, then perform pointwise operations or aggregation:

SELECT numericIndexedVectorAllValueSum(
  numericIndexedVectorPointwiseMultiply(
    groupNumericIndexedVectorMergeState(va_state),
    groupNumericIndexedVectorMergeState(vb_state)))
FROM target_table
WHERE dt BETWEEN '2026-01-01' AND '2026-01-29';

Pre-aggregation suits repeated queries over the same vectors, such as A/B experiment metrics, user profiles, order reports, and retention reports. Most of the gains in Section 4 come from this path. The cost is an additional vector-construction step during ingestion and extra AggregateFunction columns to maintain.

3.5 Practical Details

DimensionRecommendationReason
Bit widthChoose a supported type for the largest expected value; use UInt32 when 24 bits are neededBitmaps for unused high bits have little overhead, but results beyond the width need handling under the implementation’s rules
SignednessUse signed types when metrics or intermediate results can be negativeThe type is fixed at construction; later conversion requires reprocessing the vector representation
Position encodingUse the same dictionary for vectors involved in pointwise operationsInconsistent encoding mismatches different keys at the same position
OrderingKeep an ordered representation for windows, sorting, and rankingPosition encoding identifies key positions without representing business order

4. Measurements and Comparisons

The figures below come from Xiong and Wang’s paper, whose tests cover 105 core WeChat metrics over different data ranges: 29 days for storage, two days for sums, one day’s jobs for precomputation, and one week for ad-hoc queries. They measure the internal system; the community implementation has not been benchmarked separately. The main comparison is:

DimensionRow-basedNumericIndexedVectorGain
Total storage4.1 TB1.6 TB~40% of original (60% less)
Per-user sum of two days, one metric59.2 s0.6 s~100×
Precomputation CPU hoursxx / 4~4×
Average ad-hoc query latency22.3 s6.0 s~3.7×

These gains reflect changes in storage, summation, joins, and the query workflow. The following sections explain each one.

4.1 60% Less Storage: Compact Positions and Bit-Sliced Encoding

Even after aggregation by key, traditional (key, value) tables store a complete value for each distinct key. For UInt32 and UInt64, the two uncompressed columns total about 12 bytes per key. Vectors first reduce the key range through position encoding, then store each binary bit of the values in RoaringBitmap. Unused high bits are empty, and consecutive positions can use range representations. BSI already reduces the data during encoding, so adding general-purpose compression such as LZ4 or ZSTD gives limited extra benefit. The paper reports a reduction from 4.1 TB to 1.6 TB, about 60% less storage.

4.2 Sums Up to About 100 Times Faster: Bit-Sliced Operations and SIMD

A global sum counts the 1s in each bitmap and multiplies by its bit weight, without decoding individual values. numericIndexedVectorAllValueSum uses POPCOUNT for the counts. Unused high bits correspond to empty bitmaps, so counting them adds little overhead; SIMD can also process batches. The paper measures a different kind of sum: adding two days of one metric per user. With AVX2, three metrics fell from 59.2, 7.3, and 94.3 seconds to 0.6, 1.3, and 10.5 seconds, speedups of about 100, 5.6, and 9 times.

4.3 Precomputation CPU at About One Quarter: Less Row-by-Row Matching

Traditional computation first matches records by key, incurring substantial CPU and network costs at high cardinality. Shared position encoding determines the correspondence in advance, allowing queries to perform pointwise operations directly and reduce row-by-row hash joins and data redistribution. The paper reports precomputation CPU use at about one quarter of the original.

4.4 Ad-Hoc Queries About 3.7 Times Faster: Reading and Computation

Ad-hoc queries benefit mainly from reading and computation: smaller storage means less data to read, and filtering and aggregation work directly on bitmaps. The paper’s baseline already filtered the metric log with exposure bitmaps and did not join the two logs row by row; against that baseline, average query time fell from 22.3 seconds to 6.0 seconds, about a 3.7-fold speedup.

4.5 Comparing Other Representations

  • groupBitmap suits user tags and audience selection that need only set semantics. Use NumericIndexedVector when each key must carry a number.
  • Traditional (key, value) tables support more flexible grouping and queries. With fewer keys and simple queries, reading a table directly usually gives lower absolute latency.
  • For small, consecutive key ranges, such as fewer than a million consecutive IDs, dense arrays are more direct. Bitmap representations are more compact for large, nonconsecutive ranges.
  • Frequent grouping by columns other than the key, or workloads involving strings, exact decimal values, windows, and time series, need representations that support those semantics.

Wrapping Up

NumericIndexedVector gains efficiency by changing how data is organized: bucketing distributes computation, position encoding aligns keys, and BSI represents the values. For metric analysis with high-cardinality keys, this reduces storage and removes the work of matching individual keys at query time.

Shared position encoding is therefore part of the data model. It ensures that a position always identifies the same object across dates and metrics, allowing pointwise operations to combine them directly. The same approach supports 64-bit business keys: the dictionary keeps the original keys, vectors use 32-bit positions within buckets, and decoding looks up both the bucket ID and position.

These designs move some costs to ingestion. Stable encoding dictionaries must be maintained, and vectors constructed and merged, but queries can reuse the results. Repeated queries over the same data in WeChat’s metric platform are what make this trade-off deliver storage and computation gains.