In data analytics, bitmaps often represent sets of users. Intersection, union, and difference can all be computed with bitwise operations. But a bitmap records whether a key exists, without storing a numeric value for that key. To analyze each user’s dwell time, order amount, or click count, we usually keep (key, value) pairs in tables and compute the results row by row.

NumericIndexedVector provides another representation for these workloads: it uses keys as indexes and encodes values in a group of bitmaps. This preserves compact bitmap storage while supporting per-key arithmetic, comparison, and aggregation. Addition, subtraction, and comparison operate directly on the compressed bitmaps; multiplication and division decode the values, compute the results, and encode them again.

I developed NumericIndexedVector and contributed it to the ClickHouse community (PR-74193, merged in June 2025). Its algorithms come from Xiong and Wang’s paper Large-Scale Metric Computation in Online Controlled Experiment Platform. Before the contribution, the implementation had already been running at scale inside WeChat for more than a year, and other teams had studied and used it. This post explains several implementation choices alongside the underlying algorithms: why multiplication and division use decoded values, why indexes are limited to 32 bits, and why keys with a value of zero need a separate record.

Starting with bitmaps and RoaringBitmap, this post explains how BSI stores numbers, how arithmetic and comparison work with that representation, and how the ClickHouse types and functions expose it. The next post covers bucketing, position encoding, SQL rewrites, and measured results.

1. From Bitmap to RoaringBitmap

A bitmap represents a set of integers as a sequence of bits. Bit i is 1 when integer i belongs to the set and 0 otherwise. Each integer has a fixed position, so two sets can be combined directly with bitwise operations.

Set operations map to bitwise operations: AND computes intersection, OR union, XOR symmetric difference, and ANDNOT difference. POPCOUNT counts the set bits, giving the set’s cardinality. For a plain bitmap with nn positions, scanning 64, 256, or 512 bits at a time costs O(n/64)O(n/64), O(n/256)O(n/256), or O(n/512)O(n/512), respectively.

In online analytical processing (OLAP), bitmaps are commonly used for filtering sets and counting distinct values:

An inverted index represents each filter condition as a bitmap; intersecting them finds records that satisfy all the conditions. User tags can be organized in the same way, with intersection, union, and difference selecting an audience. Distinct counting records user IDs in a bitmap and counts the set bits, without a separate sort or hash table.

A plain bitmap’s storage depends on the integer range it covers, rather than the number of elements actually present. Covering the full UInt32 space requires 2322^{32} bits, or about 4.3 billion positions. It takes 512 MiB even if the set contains only a few thousand elements. RoaringBitmap avoids paying that fixed cost for empty positions through bucketing and adaptive storage. For UInt32 keys, it works as follows:

  • The high 16 bits identify a bucket, and the low 16 bits identify a position within it. Each bucket covers 2162^{16} positions.
  • With at most 4096 elements, an Array container stores a sorted array using 2 bytes per element. For larger sets, a Bitmap container uses an 8 KiB plain bitmap. When consecutive ranges are common, a Run container stores each range as (start, length).
  • AND, OR, ANDNOT, and XOR have implementations for each container type, with SIMD processing where applicable.

RoaringBitmap chooses a representation according to the data distribution while preserving set operations. Sparse sets can use arrays, dense sets bitmaps, and consecutive ranges Run containers. It has an official website and implementations in multiple languages; ClickHouse also uses it to implement AggregateFunction(groupBitmap, UInt32).

RoaringBitmap improves storage and computation, but one bitmap still represents only presence or absence. It can record whether a user was active or clicked something; recording how long the user stayed or how much they spent requires numeric values. We want those values to benefit from RoaringBitmap’s storage and, where practical, its bitmap operations.

NumericIndexedVector represents a numeric vector with several RoaringBitmaps. Each bitmap stores one binary bit of the values, extending the set representation to support numeric computation.

2. Data Analysis Query Patterns

A common analytical query joins two tables by key, then computes a function of the two values associated with each key. The key might identify a user, product, session, or device. This SQL shows the basic pattern:

SELECT A.key, f(A.val_a, B.val_b)
FROM A JOIN B ON A.key = B.key;

With tens or hundreds of millions of distinct keys, joins and row-by-row computation consume substantial resources. In products with more than 100 million daily active users, daily metric computation involves PB-scale I/O and millions of CPU core-hours. A distributed hash join also redistributes both tables by key, a step known as shuffle. After matching the rows, it evaluates f for each row, then processes and sums the results.

A vector representation can reduce this matching cost. Represent val_a and val_b as vectors indexed by key. When both vectors use the same key encoding, the same position identifies the same key. Computation can align those positions directly, without matching individual rows. Operations applied separately at each position are called pointwise operations, such as adding or multiplying two metrics for the same user.

BSI extends bitmap set representations to numeric values, allowing computation on aligned positions for integers and fixed-point fractions.

3. The Core Idea of NumericIndexedVector

NumericIndexedVector encodes values using a Bit-Sliced Index (BSI). The paper Large-Scale Metric Computation in Online Controlled Experiment Platform applies this representation to large-scale experiment metric computation.

Consider (key: UInt32, value: UInt64) pairs. A UInt64 value has at most 64 binary bits, so we prepare 64 bitmaps, denoted B0,B1,…,B63B_0, B_1, \ldots, B_{63}. BiB_i records every key whose value has a 1 at bit ii, rather than storing the full value for any one key.

Bi[j]=1B_i[j] = 1 means that the value for key jj has a 1 at binary bit ii.

To recover the value for key jj, read its corresponding bit from each bitmap and sum them with weights 2i2^i. Together, those bits form the complete value for that key:

C[j]  =  ∑i=063Bi[j]⋅2iC[j] \;=\; \sum_{i=0}^{63} B_i[j] \cdot 2^i

A Small Example

Suppose four keys, 0, 1, 2, 3, have values 5, 2, 7, 0. These values need at most three binary bits, so three bitmaps can represent them:

key jvaluebit 2bit 1bit 0
05 (101)101
12 (010)010
27 (111)111
30 (000)000

Collect the keys with a 1 in each column:

  • B0={0,2}B_0 = \{0, 2\}: keys 0 and 2 have a 1 at bit 0.
  • B1={1,2}B_1 = \{1, 2\}: keys 1 and 2 have a 1 at bit 1.
  • B2={0,2}B_2 = \{0, 2\}: keys 0 and 2 have a 1 at bit 2.

Key 0 appears in B0B_0 and B2B_2, giving 1+4=51 + 4 = 5. Key 2 appears in all three bitmaps, giving 1+2+4=71 + 2 + 4 = 7. Key 3 has a value of zero and appears in none of the BSI bitmaps; this is why we will need zero_indexes later.

Putting the Representation Together

The original BSI represents nonnegative integers. NumericIndexedVector extends it to negative values with two’s complement, as explained in Section 5.

Real values use fixed-point encoding: the low ff bits represent the fractional part, and the stored value is truncated to an integer after multiplication by 2f2^f. With 64 storage bits and 14 fractional bits, the smallest step is 2−14≈6.1×10−52^{-14} \approx 6.1 \times 10^{-5}, and the quantization error per value is less than one step. The remaining 50 bits hold the integer part, with a maximum of about 1.1×10151.1 \times 10^{15}. Metrics that require exact decimal values, such as money, can first be converted to integers in a fixed unit, such as cents; multiplication, division, and sums still go through Float64, so very large values also need a precision check.

Each BiB_i is an independent RoaringBitmap and can reuse its compressed storage and SIMD operations. The next post explains how bucketing and position encoding reduce storage further.

A NumericIndexedVector consists of an ordered sequence of RoaringBitmaps and metadata such as bit width and signedness. Each bitmap stores the same binary bit across all keys, so one bitmap operation processes many keys at once. The following algorithms all use this property.

4. Bit-Level Algorithms: Addition, Subtraction, Multiplication, Comparison, and Division

Below, ^ / & / &~ / | denote bitmap XOR, AND, ANDNOT, and OR. Input vectors X and Y each contain NN bitmaps, ordered from low to high bits as X[0]..X[N-1] and Y[0]..Y[N-1]. These algorithms extend binary arithmetic on individual values to batches of keys. The pseudocode follows Large-Scale Metric Computation in Online Controlled Experiment Platform. The multiplication and division sections also explain how the ClickHouse implementation differs from the bit-level approach.

4.1 Addition: A Full Adder with Bitmap Operations

In binary addition, a full adder takes the current input bits XiX_i and YiY_i, together with the carry Cin from the lower bit. It computes both the sum bit SiS_i and the carry Cout for the higher bit:

Sᵢ   = Xᵢ ^ Yᵢ ^ Cin
Cout = (Xᵢ & Yᵢ) | (Cin & (Xᵢ ^ Yᵢ))

In BSI, XiX_i and YiY_i correspond to the bitmaps at bit ii. Replacing the logical operations with bitmap operations lets the same formulas compute sums and carries for all keys at that bit. Iterating from low to high bits completes the vector addition:

input:  X[0..N-1], Y[0..N-1]
output: S[0..N-1]

bitmap Cin = empty;
for i in 0..N-1:
    S[i] = X[i] ^ Y[i] ^ Cin;
    Cin  = (X[i] & Y[i]) | (Cin & (X[i] ^ Y[i]));

Addition runs for NN iterations, each requiring a constant number of bitmap operations. Its total complexity is O(N⋅∣B∣op)O(N \cdot |B|_{\text{op}}), where ∣B∣op|B|_{\text{op}} is the cost of one bitmap operation. The result retains NN bits. For unsigned values, if Cin is nonempty after the highest bit, some keys have overflowed; the result must be truncated or stored at a wider output width.

4.2 Subtraction: Borrow Instead of Carry

Subtraction has the same structure as addition, but propagates a borrow Bin. A full subtractor computes the difference bit DiD_i and the next borrow Bout from the current input bits and borrow:

Dᵢ   = Xᵢ ^ Yᵢ ^ Bin
Bout = ((Yᵢ | Bin) &~ Xᵢ) | (Bin & Yᵢ)

Replacing individual bits with bitmaps gives vector subtraction:

input:  X[0..N-1], Y[0..N-1]
output: D[0..N-1]

bitmap Bin = empty;
for i in 0..N-1:
    D[i] = X[i] ^ Y[i] ^ Bin;
    Bin  = ((Y[i] | Bin) &~ X[i]) | (Bin & Y[i]);

For unsigned values, a borrow remaining after the highest bit means X < Y. Thus, the final Bin is also the result bitmap for a less-than comparison, without computing the difference again.

4.3 Multiplication: Shift and Accumulate

Binary multiplication follows the familiar long-multiplication procedure. For each bit i of Y, use Y[i] to select the keys in X that contribute to this iteration, shift the result left by i bits, and add it to M. Each iteration reuses the addition algorithm:

input:  X[0..N-1], Y[0..N-1]
output: M[0..2N-1]              // result is up to 2N bits wide

bitmap M[2N] = {empty};
for i in 0..N-1:
    if Y[i] is empty: continue;
    bitmap S[N];
    for j in 0..N-1:
        S[j] = X[j] & Y[i];
    bitmap Cin = empty, tmp;
    for k in i..i+N-1:
        tmp  = M[k] ^ S[k-i] ^ Cin;
        Cin  = (M[k] & S[k-i]) | (Cin & (M[k] ^ S[k-i]));
        M[k] = tmp;
    M[i+N] = Cin;               // the remaining carry goes into the next higher bit

The outer loop visits each bit of Y; the inner loop adds the shifted result. Multiplying two NN-bit values can require 2N bits for the complete product. If the output width is smaller, truncation must follow the chosen rules.

⚙️ Implementation trade-off: Bit-level multiplication performs one addition for each bit of Y, for a total cost of roughly O(N2⋅∣B∣op)O(N^2 \cdot |B|_{\text{op}}). The ClickHouse implementation instead decodes both vectors into (key, value) arrays, multiplies the matching values as Float64, and encodes the result back into BSI. This adds decoding and encoding but reduces bitmap operations. In practical use, the two paths differ in performance by about an order of magnitude. See pointwiseRawBinaryOperate in AggregateFunctionGroupNumericIndexedVectorDataBSI.h.

4.4 Comparison: Borrow for Ordering, Bits for Equality

As the subtraction algorithm shows, the final borrow determines the ordering of unsigned values. Keeping only the borrow computation produces L, the result of X < Y:

// L = 1 means X[j] < Y[j]
bitmap L = empty;
for i in 0..N-1:
    L = ((Y[i] | L) &~ X[i]) | (L & Y[i]);

Swapping X and Y computes X > Y. Signed values also require checking the sign bit, as discussed in Section 5.

Equality checks whether the values differ at any bit. If a bit differs, that key cannot satisfy equality. Start with a candidate key set U and remove keys whose bits differ:

// E = 1 means X[j] == Y[j]
// U is the non-zero key set of the sparser side of X or Y (keys non-zero on both sides only)
bitmap E = U;
for i in 0..N-1:
    E = E &~ (X[i] ^ Y[i]);

To show the principle, this handles only keys that are non-zero on both sides; zero-valued keys are handled separately through zero_indexes, described later. Inequality is the complement of E within the union of both sides’ keys. For <= and >=, take the union of the less-than or greater-than result, respectively, with the equality result. Here is <=:

bitmap L = empty;
bitmap E = U;
for i in 0..N-1:
    L = ((Y[i] | L) &~ X[i]) | (L & Y[i]);
    E = E &~ (X[i] ^ Y[i]);
LE = L | E;

A comparison result can serve as a filter mask with values of 0 or 1: qualifying keys get 1, and the others get 0. Multiplying this mask by a numeric vector with numericIndexedVectorPointwiseMultiply retains the qualifying values. The next post uses this approach to rewrite conditional sums.

4.5 Division: Computing the Quotient One Bit at a Time

Bit-level division can use restoring binary long division, illustrated in sistenix’s tutorial. Starting at the highest quotient bit, each iteration shifts, compares, and subtracts conditionally:

  • Shift the divisor YY left by ii bits to obtain Y<<iY << i.
  • Compare the current remainder XX with the shifted divisor to determine which keys have a 1 at quotient bit ii.
  • For those keys, subtract Y<<iY << i from XX, update the remainder, and continue to the next bit.

Fixed-point division must also preserve fractional precision. In the bit-level approach, first shift the dividend XX left by decimal_bm_num bits, align the bit widths and fractional widths of the dividend and divisor, and then run the loop:

input:  X[0..N-1], Y[0..N-1]      // dividend X, divisor Y (aligned to N bits)
output: Q[0..N-1]                  // quotient

bitmap Q[N] = {empty};

// Pre-shift Y all the way left; each loop iteration shifts back right by 1
// so that Y at iteration i is (original Y) << i
Y = shift_left(Y, N);

for i in N-1 .. 0:
    Y = shift_right(Y, 1);             // now Y == (original Y) << i

    // Compare: a_i = X >= Y — a {0, 1}-valued bitmap, the i-th quotient bit
    Q[i] = isGreaterOrEqual(X, Y);

    // Masked subtract: only on keys where Q[i] = 1
    masked_Y[0..N-1] = { Y[j] & Q[i] for j in 0..N-1 };
    X = subtract(X, masked_Y);

Bit-level division runs for NN iterations, each containing a comparison and a masked subtraction. Both take O(N)O(N) rounds of bitmap operations, so the total complexity is roughly O(N2⋅∣B∣op)O(N^2 \cdot |B|_{\text{op}}). Computing each quotient bit scans several bitmaps, making division more expensive than addition or subtraction.

This approach must also exclude keys present in the dividend but lacking a valid divisor. Taking the union of the divisor’s bitmaps and intersecting it with the dividend’s key set filters those positions before computation.

⚙️ Implementation trade-off: ClickHouse division shares the pointwiseRawBinaryOperate path with multiplication: decode both vectors, divide matching values as Float64, and encode the result back into BSI. Bit-level long division explains how the representation supports division, while the actual interface uses decode → compute → encode to reduce the cost of bit-level loops.

5. Bit Width and Signed Values

Fixing the Bit Width at Construction

The original BSI can choose the number of bitmaps according to the values being stored. NumericIndexedVector fixes the bit width N and signedness at construction, much like C++ integer types.

Operations can therefore iterate directly over 0..N-1, without determining the bitmap count at runtime. Unused high bits correspond to empty bitmaps, which retain only a small amount of metadata and can be processed quickly. Vectors used together in a pointwise operation must have the same bit width or be converted first.

For example, if every value in a UInt32 vector lies in [0, 255], all bitmaps from bit 8 upward are empty and serialize to only a small amount of header data. Storage cost depends primarily on the bits actually used, rather than the declared width. Reserving some extra integer bits therefore does not usually increase storage in proportion to the width.

Signed Integers: Two’s Complement

Signed integers use two’s complement, following the binary arithmetic rules of ordinary integers:

  • The highest bit indicates the sign.
  • Addition and subtraction use the same recurrence formulas; carries beyond the width follow the truncation rules.
  • Multiplication handles signs separately, for example by computing an unsigned product and then determining its sign from the two inputs.
  • Comparison checks signs first; when the signs differ, a negative value is less than a nonnegative value.

Overflow and division by zero are handled according to the implementation’s rules. The relevant branches are available in PR-74193.

Real Values: Fixed-Point Defaults

Section 3 used 14 fractional bits to illustrate fixed-point encoding. Float32 and Float64 inputs use a default of 40 integer bits and 24 fractional bits, defined by constants in BSINumericIndexedVector:

DimensionDefaultMeaning
DEFAULT_INTEGER_BIT_NUM40Integer width: signed range of ±239≈±5.5×1011\pm 2^{39} \approx \pm 5.5 \times 10^{11}, covering most business metrics such as amounts, counts, and durations
DEFAULT_FRACTION_BIT_NUM24Fractional width: smallest step 2−24≈5.96×10−82^{-24} \approx 5.96 \times 10^{-8}, about 7 decimal places
MAX_TOTAL_BIT_NUM64Hard constraint: integer_bit_num + fraction_bit_num ≤ 64
MAX_FRACTION_BIT_NUM24Maximum fractional width: greater precision adds storage and computation with little value for these analytical workloads

The default of 40 integer bits and 24 fractional bits comes from practical workloads: the integer part covers common metric magnitudes, and the fractional part provides a step of approximately 5.96×10−85.96 \times 10^{-8}.

In IEEE 754 floating point, the exponent determines the weight of each significand bit. The same significand bit can represent different magnitudes across values, so the BSI arithmetic above cannot be applied directly. Fixed-point encoding gives all values the same scale, allowing each bitmap to have a consistent bit weight.

Zero Values and Missing Keys: Recording zero_indexes

In ordinary BSI, a key with value zero appears in none of the bitmaps, making it look the same as a missing key. But analytics must distinguish a user whose top-up amount is zero from a user absent from the data. NumericIndexedVector therefore adds a separate zero_indexes bitmap:

data_array stores the BSI bitmaps at the declared width, encoding nonzero values; zero_indexes records keys explicitly present with a value of zero.

Counting keys must include both nonzero and zero-valued keys, by taking the union of data_array_keys and zero_indexes. When retrieving a key absent from all BSI bitmaps, we must also check zero_indexes to distinguish zero from absence.

This also preserves correctness across multiple computation steps. An intermediate result of zero should not remove a key from subsequent computations. Recording zero values separately preserves the key’s presence when computation continues.

6. ClickHouse Interfaces: Types, Aggregate Functions, and Regular Functions

ClickHouse’s NumericIndexedVector interface has three parts: a type stores the vector, aggregate functions construct and merge it, and regular functions compute results and extract values. Their relationship is shown below:

┌───────────────────────────────────────────┐
│  Data type                                │
│  AggregateFunction(                       │
│    groupNumericIndexedVector, ...)        │
└───────────────────────────────────────────┘
           ▲                    ▲
           │                    │
┌──────────┴────────┐  ┌────────┴───────────┐
│  Aggregate funcs  │  │  Regular UDFs      │
│  group... family  │  │  pointwise / cmp   │
│  (State/Merge/    │  │  / extract / agg   │
│   Finalize)       │  │                    │
└───────────────────┘  └────────────────────┘

Data Type

The vector uses ClickHouse’s AggregateFunction(...) type. The key type comes first, followed by the value type:

  • Key types: UInt8/16/32 and their signed counterparts, Int8/16/32. The index is used directly as a bitmap position. The implementation uses 32-bit RoaringBitmap to avoid the performance cost of the 64-bit implementation. About 4.3 billion positions cover user-level analytics for WeChat’s more than one billion daily active users. For 64-bit business keys, map them to 32-bit position codes first; Section 1.3 of the next post explains how.
  • Value types: UInt8/16/32/64, their signed counterparts, and Float32 / Float64. This type determines the bit width, signedness, and whether fixed-point encoding is used.

For example, a vector with UInt32 keys and UInt64 values has this type:

AggregateFunction(groupNumericIndexedVector, UInt32, UInt64)
-- key=UInt32, value=UInt64

Float32 and Float64 values use the fixed-point encoding described above, with 40 integer bits and 24 fractional bits.

Aggregate Functions: The group... Family

  • groupNumericIndexedVector(key, value): constructs a vector by key, summing values for repeated keys. Without a suffix, the final result is the sum of all values, returned as Float64.
  • groupNumericIndexedVectorState(...): returns the vector’s aggregate state, accepted by subsequent pointwise, comparison, and extraction functions. It can also be stored in an AggregateFunction column for materialized views and pre-aggregation tables, as shown in the next post.
  • numericIndexedVectorBuild(map): constructs a vector directly from a Map, without an aggregation query.

Regular Functions

Regular functions take a constructed vector and fall into four groups:

Per-key arithmetic supports both vector–vector and vector–scalar operations.

  • numericIndexedVectorPointwiseAdd / Subtract / Multiply / Divide

Per-key comparison produces a 0/1 vector that can serve as a filter mask.

  • numericIndexedVectorPointwiseEqual / NotEqual
  • numericIndexedVectorPointwiseLess / LessEqual / Greater / GreaterEqual

Extraction:

  • numericIndexedVectorGetValue(v, key): retrieves the value for one key.
  • numericIndexedVectorToMap(v): decodes the entire vector into Map(key, value).

Aggregation produces a scalar:

  • numericIndexedVectorAllValueSum(v): sums all values.
  • numericIndexedVectorCardinality(v): counts distinct keys, including explicitly recorded zero-valued keys.

Per-key minimum and maximum, along with global minimum and maximum, are subsequent extensions (PR-88840). The semantics of numericIndexedVectorPointwiseMin / Max can also be expressed by combining comparison, multiplication, and addition, but dedicated functions reduce the creation of intermediate vectors.

Wrapping Up

BSI represents the binary bits of numeric values in separate bitmaps, allowing numeric analytics to reuse RoaringBitmap’s storage and computation. Its storage benefits come from two properties: sparse keys do not fill the entire position space, and unused high bits do not require storing a complete integer for each key.

The cost of bit width is uneven. Reserved high integer bits that remain zero correspond to empty bitmaps. Increasing fractional precision, however, records more low-bit information and adds storage and computation. The default of 24 fractional bits reflects the balance between the precision that business workloads require and its cost.

Addition, subtraction, and comparison operate directly on bitmaps; multiplication and division use decoding, Float64 computation, and re-encoding. zero_indexes preserves keys with a value of zero, so objects whose intermediate results become zero can continue to participate in later computations. These choices let BSI represent both numeric values and the semantics needed for analysis.

The next post applies this representation to real queries: bucketing and position encoding, applicable scenarios, three SQL rewrite patterns, pre-aggregation, and the paper’s storage and query results.