Git Product home page Git Product logo

postgresql-hll's Introduction

Build Status

Overview

This Postgres module introduces a new data type hll which is a HyperLogLog data structure. HyperLogLog is a fixed-size, set-like structure used for distinct value counting with tunable precision. For example, in 1280 bytes hll can estimate the count of tens of billions of distinct values with only a few percent error.

In addition to the algorithm proposed in the original paper, this implementation is augmented to improve its accuracy and memory use without sacrificing much speed. See below for more details.

This postgresql-hll extension was originally developed by the Science team from Aggregate Knowledge, now a part of Neustar. Please see the acknowledgements section below for details about its contributors.

Algorithms

A hll is a combination of different set/distinct-value-counting algorithms that can be thought of as a hierarchy, along with rules for moving up that hierarchy. In order to distinguish between said algorithms, we have given them names:

EMPTY

A constant value that denotes the empty set.

EXPLICIT

An explicit, unique, sorted list of integers in the set, which is maintained up to a fixed cardinality.

SPARSE

A 'lazy', map-based implementation of HyperLogLog, a probabilistic set data structure. Only stores the indices and values of non-zero registers in a map, until the number of non-zero registers exceeds a fixed cardinality.

FULL

A fully-materialized, list-based implementation of HyperLogLog. Explicitly stores the value of every register in a list ordered by register index.

Motivation

Our motivation for augmenting the original HLL algorithm went something like this:

  • Naively, a HLL takes regwidth * 2^log2m bits to store.
  • In typical usage, log2m = 11 and regwidth = 5, it requires 10,240 bits or 1,280 bytes.
  • That's a lot of bytes!

The first addition to the original HLL algorithm came from realizing that 1,280 bytes is the size of 160 64-bit integers. So, if we wanted more accuracy at low cardinalities, we could just keep an explicit set of the inputs as a sorted list of 64-bit integers until we hit the 161st distinct value. This would give us the true representation of the distinct values in the stream while requiring the same amount of memory. (This is the EXPLICIT algorithm.)

The second came from the realization that we didn't need to store registers whose value was zero. We could simply represent the set of registers that had non-zero values as a map from index to values. This map is stored as a list of index-value pairs that are bit-packed "short words" of length log2m + regwidth. (This is the SPARSE algorithm.)

Combining these two augmentations, we get a "promotion hierarchy" that allows the algorithm to be tuned for better accuracy, memory, or performance.

Initializing and storing a new hll object will simply allocate a small sentinel value symbolizing the empty set (EMPTY). When you add the first few values, a sorted list of unique integers is stored in an EXPLICIT set. When you wish to cease trading off accuracy for memory, the values in the sorted list are "promoted" to a SPARSE map-based HyperLogLog structure. Finally, when there are enough registers, the map-based HLL will be converted to a bit-packed FULL HLL structure.

Empirically, the insertion rate of EMPTY, EXPLICIT, and SPARSE representations is measured in 200k/s - 300k/s range, while the throughput of the FULL representation is in the millions of inserts per second on relatively new hardware ('10 Xeon).

Naturally, the cardinality estimates of the EMPTY and EXPLICIT representations is exact, while the SPARSE and FULL representations' accuracies are governed by the guarantees provided by the original HLL algorithm.


Usage

"Hello World"

--- Make a dummy table
CREATE TABLE helloworld (
        id              integer,
        set     hll
);

--- Insert an empty HLL
INSERT INTO helloworld(id, set) VALUES (1, hll_empty());

--- Add a hashed integer to the HLL
UPDATE helloworld SET set = hll_add(set, hll_hash_integer(12345)) WHERE id = 1;

--- Or add a hashed string to the HLL
UPDATE helloworld SET set = hll_add(set, hll_hash_text('hello world')) WHERE id = 1;

--- Get the cardinality of the HLL
SELECT hll_cardinality(set) FROM helloworld WHERE id = 1;

Now with the silly stuff out of the way, here's a more realistic use case.

Data Warehouse Use Case

Let's assume I've got a fact table that records users' visits to my site, what they did, and where they came from. It's got hundreds of millions of rows. Table scans take minutes (or at least lots and lots of seconds.)

CREATE TABLE facts (
  date            date,
  user_id         integer,
  activity_type   smallint,
  referrer        varchar(255)
);

I'd really like a quick (milliseconds) idea of how many unique users are visiting per day for my dashboard. No problem, let's set up an aggregate table:

-- Create the destination table
CREATE TABLE daily_uniques (
  date            date UNIQUE,
  users           hll
);

-- Fill it with the aggregated unique statistics
INSERT INTO daily_uniques(date, users)
  SELECT date, hll_add_agg(hll_hash_integer(user_id))
  FROM facts
  GROUP BY 1;

We're first hashing the user_id, then aggregating those hashed values into one hll per day. Now we can ask for the cardinality of the hll for each day:

SELECT date, hll_cardinality(users) FROM daily_uniques;

You're probably thinking, "But I could have done this with COUNT DISTINCT!" And you're right, you could have. But then you only ever answer a single question: "How many unique users did I see each day?"

What if you wanted to this week's uniques?

SELECT hll_cardinality(hll_union_agg(users)) FROM daily_uniques WHERE date >= '2012-01-02'::date AND date <= '2012-01-08'::date;

Or the monthly uniques for this year?

SELECT EXTRACT(MONTH FROM date) AS month, hll_cardinality(hll_union_agg(users))
FROM daily_uniques
WHERE date >= '2012-01-01' AND
      date <  '2013-01-01'
GROUP BY 1;

Or how about a sliding window of uniques over the past 6 days?

SELECT date, #hll_union_agg(users) OVER seven_days
FROM daily_uniques
WINDOW seven_days AS (ORDER BY date ASC ROWS 6 PRECEDING);

Or the number of uniques you saw yesterday that you didn't see today?

SELECT date, (#hll_union_agg(users) OVER two_days) - #users AS lost_uniques
FROM daily_uniques
WINDOW two_days AS (ORDER BY date ASC ROWS 1 PRECEDING);

These are just a few examples of the types of queries that would return in milliseconds in an hll world from a single aggregate, but would require either completely separate pre-built aggregates or self-joins or generate_series trickery in a COUNT DISTINCT world.

Operators

We've added a few operators to make using hlls less cumbersome/verbose. They're simple aliases for the most commonly used functions.

Function Operator Example
hll_add || hll_add(users, hll_hash_integer(123))
or
users || hll_hash_integer(123)
or
hll_hash_integer(123) || users
hll_cardinality # hll_cardinality(users)
or
#users
hll_union || hll_union(male_users, female_users)
or
male_users || female_users
or
female_users || male_users

Hashing

You'll notice that all the calls to hll_add or || involve wrapping the input value in a hll_hash_[type] call; it's absolutely crucial that you hash your input values to hll structures. For more on this, see the section below titled 'The Importance of Hashing'.

The hashing functions we've made available are listed below:

Function Input Example
hll_hash_boolean boolean hll_hash_boolean(TRUE)
or
hll_hash_boolean(TRUE, 123/*hash seed*/)
hll_hash_smallint smallint hll_hash_smallint(4)
or
hll_hash_smallint(4, 123/*hash seed*/)
hll_hash_integer integer hll_hash_integer(21474836)
or
hll_hash_integer(21474836, 123/*hash seed*/)
hll_hash_bigint bigint hll_hash_bigint(223372036854775808)
or
hll_hash_bigint(223372036854775808, 123/*hash seed*/)
hll_hash_bytea bytea hll_hash_bytea(E'\\xDEADBEEF')
or
hll_hash_bytea(E'\\xDEADBEEF', 123/*hash seed*/)
hll_hash_text text hll_hash_text('foobar')
or
hll_hash_text('foobar', 123/*hash seed*/)
hll_hash_any any hll_hash_any(anyval)
or
hll_hash_any(anyval, 123/*hash seed*/)

NOTE: hll_hash_any dynamically dispatches to the appropriate type-specific function, which makes it slower than the type-specific ones it wraps. Use it only when the input type is not known beforehand.

So what if you don't want to hash your input?

postgres=# select 1234 || hll_empty();
ERROR:  operator does not exist: integer || hll
LINE 1: select 1234 || hll_empty();
                    ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Not pretty. Since hashing is such a crucial part of the accuracy of HyperLogLog, we decided to "enforce" this at a type level. You can only add hll_hashval typed things to a hll, which is what the hll_hash_[type] functions return. You can simply cast integer values to hll_hashval to add them without hashing, like so:

postgres=# select 1234::hll_hashval || hll_empty();
         ?column?
--------------------------
 \x128c4900000000000004d2
(1 row)

Aggregate functions

If you want to create a hll from a table or result set, use hll_add_agg. The naming here isn't particularly creative: it's an aggregate function that adds the values to an empty hll.

SELECT date, hll_add_agg(hll_hash_integer(user_id))
FROM facts
GROUP BY 1;

The above example will give you a hll for each date that contains each day's users.

If you want to summarize a list of hlls that you already have stored into a single hll, use hll_union_agg. Again: it's an aggregate function that unions the values into an empty hll.

SELECT EXTRACT(MONTH FROM date), hll_cardinality(hll_union_agg(users))
FROM daily_uniques
GROUP BY 1;

Sliding windows are another prime example of the power of hlls. Doing sliding window unique counting typically involves some generate_series trickery, but it's quite simple with the hlls you've already computed for your roll-ups.

SELECT date, #hll_union_agg(users) OVER seven_days
FROM daily_uniques
WINDOW seven_days AS (ORDER BY date ASC ROWS 6 PRECEDING);

Explanation of Parameters and Tuning

log2m

The log-base-2 of the number of registers used in the HyperLogLog algorithm. Must be at least 4 and at most 31. This parameter tunes the accuracy of the HyperLogLog structure. The relative error is given by the expression ±1.04/√(2log2m). Note that increasing log2m by 1 doubles the required storage for the hll.

regwidth

The number of bits used per register in the HyperLogLog algorithm. Must be at least 1 and at most 8. This parameter, in conjunction with log2m, tunes the maximum cardinality of the set whose cardinality can be estimated. For clarity, we've provided a table of regwidths and log2ms and the approximate maximum cardinality that can be estimated with those parameters. (The size of the resulting structure is provided as well.)

logm2regwidth=1regwidth=2regwidth=3regwidth=4regwidth=5regwidth=6
107.4e+02   128B3.0e+03   256B4.7e+04   384B1.2e+07   512B7.9e+11   640B3.4e+21   768B
111.5e+03   256B5.9e+03   512B9.5e+04   768B2.4e+07   1.0KB1.6e+12   1.2KB6.8e+21   1.5KB
123.0e+03   512B1.2e+04   1.0KB1.9e+05   1.5KB4.8e+07   2.0KB3.2e+12   2.5KB1.4e+22   3KB
135.9e+03   1.0KB2.4e+04   2.0KB3.8e+05   3KB9.7e+07   4KB6.3e+12   5KB2.7e+22   6KB
141.2e+04   2.0KB4.7e+04   4KB7.6e+05   6KB1.9e+08   8KB1.3e+13   10KB5.4e+22   12KB
152.4e+04   4KB9.5e+04   8KB1.5e+06   12KB3.9e+08   16KB2.5e+13   20KB1.1e+23   24KB
164.7e+04   8KB1.9e+05   16KB3.0e+06   24KB7.7e+08   32KB5.1e+13   40KB2.2e+23   48KB
179.5e+04   16KB3.8e+05   32KB6.0e+06   48KB1.5e+09   64KB1.0e+14   80KB4.4e+23   96KB

expthresh

Tunes when the EXPLICIT to SPARSE promotion occurs, based on the set's cardinality. It is also possible to turn off the use of the EXPLICIT representation entirely. If the EXPLICIT representation is turned off, the EMPTY set is promoted directly to SPARSE. Must be -1, 0, or 1-18 inclusive.

expthresh valueMeaning
-1Promote at whatever cutoff makes sense for optimal memory usage. ('auto' mode)
0Skip EXPLICIT representation in hierarchy.
1-18Promote at 2expthresh - 1 cardinality

You can choose the EXPLICIT cutoff such that it will end up taking more memory than a FULL hll representation. This is allowed for those cases where perfect precision and accuracy are required up through some pre-set cardinality range, after which estimates of the cardinality are sufficient.

NOTE: The restriction of expthresh to a maximum value of 18 (for the third case in the table above) is an implementation tradeoff between performance and general appeal. If you want access to higher expthresh values, let us know in the Issues section and we'll see what we can do.

sparseon

Enables or disables the SPARSE representation. If both the EXPLICIT and SPARSE representations are disabled, an EMPTY set will be promoted directly to a FULL set. If SPARSE is enabled, the promotion from SPARSE to FULL will occur when the internal SPARSE representation's memory footprint would exceed that of the FULL version. Must be either 0 (zero) or 1 (one). Zero means disabled, one is enabled.

Defaults

In all the examples above, the type hll has been used without adornment. This is a shortcut. In reality, the type can have up to 4 arguments. The defaults are shown as well.

hll(log2m=11, regwidth=5, expthresh=-1, sparseon=1)

You can provide any prefix of the full list of arguments. The named arguments are the same as those mentioned in the 'Explanation of Parameters' section, above. If you'd like to change these (they're hardcoded in the source) look in hll.c for DEFAULT_LOG2M and that should get you there pretty quickly.

Debugging

hll_print is your friend! It will show you all the parameters of the hll as well as nicely-formatted representation of the contents.


Compatibility

This module has been tested on:

  • Postgres 9.4, 9.5, 9.6, 10, 11, 12, 13, 14, 15, 16

If you end up needing to change something to get this running on another system, send us the diff and we'll try to work it in!

Note: At the moment postgresql-hll does not work with 32bit systems.

Build

With rpmbuild

Specify versions:

export VER=2.18
export PGSHRT=11

Make sure Makefile points to the correct pg_config for the specified version, since rpmbuild doesn't respect env variables:

PG_CONFIG = /usr/pgsql-11/bin/pg_config

Create a tarball from the source tree:

tar cvfz postgresql${PGSHRT}-hll-${VER}.tar.gz postgresql-hll \
    --transform="s/postgresql-hll/postgresql${PGSHRT}-hll/g"

Execute rpmbuild:

rpmbuild -tb postgresql${PGSHRT}-hll-${VER}.tar.gz

Install RPM:

rpm -Uv rpmbuild/RPMS/x86_64/postgresql11-hll-2.18.x86_64.rpm

And if you want the debugging build:

rpm -Uv rpmbuild/RPMS/x86_64/postgresql11-hll-debuginfo-2.18.x86_64.rpm

From source

If you aren't using the pg_config on your path (or don't have it on your path), specify the correct one to build against:

    PG_CONFIG=/usr/pgsql-9.11/bin/pg_config make

Or to build with what's on your path, just:

    make

If you wish to build with an alternate C/C++ compiler, say gcc, then you can specify it like so:

    make CC=gcc CXX=gcc

(This may be useful if an older clang is the default compiler.)

Or for the debug build:

    DEBUG=1 make

Then install:

    sudo make install

Troubleshooting source install

You need postgresql's libraries and headers for C lang available in order to install from source. If you don't have these, you may encounter No such file or directory errors and will not be able to run the make step above. This step may depend on your OS but to install them on Debian variants use you may use:

    sudo apt-get install postgresql-server-dev-<YOUR_VERSION>

Install

After you've built and installed the artifacts, fire up psql:

    postgres=# CREATE EXTENSION hll;
    CREATE EXTENSION

And then just verify it's there:

    postgres=# \dx
                        List of installed extensions
      Name   | Version |   Schema   |            Description
    ---------+---------+------------+-----------------------------------
     hll     | 2.18    | public     | type for storing hyperloglog data
     plpgsql | 1.0     | pg_catalog | PL/pgSQL procedural language
    (2 rows)

Tests

Start a PostgreSQL server running in default port:

initdb -D data
pg_ctl -D data -l logfile -c start

Run the tests:

make installcheck

The Importance of Hashing

In brief, it is absolutely crucial to hash inputs to the hll. A close approximation of uniform randomness in the inputs ensures that the error guarantees laid out in the original paper hold. In fact, the canonical C++ implementation of MurmurHash 3 is provided in this module to facilitate this input requirement. We've empirically determined that MurmurHash 3 is an excellent and fast hash function to use in conjunction with the hll module.

The seed to the hash call must remain constant for all inputs to a given hll. Similarly, if you plan to compute the union of two hlls, the input values must have been hashed using the same seed.

For a good overview of the importance of hashing and hash functions when using probabilistic algorithms as well as an analysis of MurmurHash 3, see these four blog posts:

On Unions and Intersections

hlls have the useful property that the union of any number of hlls is equal to the hll that would have been populated by playing back all inputs to those N hlls into a single hll. Colloquially, we say that hlls have "lossless" unions because the same cardinality error guarantees that apply to a single hll apply to a union of hlls. This property combined with Postgres' aggregation functions (sliding window and so on) can power some pretty impressive analytics, like the number of unique visitors in a 30-day sliding window over the course of a year. See the hll_union_agg and hll_union functions.

Using the inclusion-exclusion principle and the union function, you can also estimate the intersection of sets represented by hlls. Note, however, that error is proportional to the union of the two hlls, while the result can be significantly smaller than the union, leading to disproportionately large error relative to the actual intersection cardinality. For instance, if one hll has a cardinality of 1 billion, while the other has a cardinality of 10 million, with an overlap of 5 million, the intersection cardinality can easily be dwarfed by even a 1% error estimate in the larger hlls cardinality.

For more information on hll intersections, see this blog post.

Storage formats

hlls are stored in the database as byte arrays, which are packed according to the storage specification, v1.0.0.

It is a pretty trivial task to export these to and from Postgres and other applications by implementing a serializer/deserializer. We have provided several packages that provide such tools:

Acknowledgements

Original developers of postgresql-hll are Ken Sedgwick, Timon Karnezos, and Rob Grzywinski.

postgresql-hll's People

Contributors

0xflotus avatar alberts avatar df7cb avatar emelsimsek avatar furkansahin avatar gmcquillan avatar gokhangulbiz avatar hanefi avatar hidva avatar jasonmp85 avatar jeffjanes avatar jeltef avatar karry avatar kostiantyn-nemchenko avatar ksedgwic avatar marcocitus avatar marcoslot avatar metdos avatar onurctirtir avatar pdgonzalez872 avatar petere avatar ragnar-ouchterlony avatar saittalhanisanci avatar serprex avatar the-alchemist avatar velioglu avatar yagelix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postgresql-hll's Issues

PostgreSQL 10 compatibility

Hello!
I get the following error when trying to build with PostgreSQL 10

osboxes@osboxes:~/workspace/postgresql-hll$ make
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fpic -std=c99 -fPIC -I. -I./ -I/usr/local/pgsql/include/server -I/usr/local/pgsql/include/internal -D_GNU_SOURCE -I/usr/include/libxml2   -c -o hll.o hll.c
In file included from /usr/local/pgsql/include/server/funcapi.h:19:0,
                 from hll.c:25:
hll.c: In function ‘hll_in’:
hll.c:1492:36: error: ‘byteain’ undeclared (first use in this function)
     Datum dd = DirectFunctionCall1(byteain, PG_GETARG_DATUM(0));
                                    ^
/usr/local/pgsql/include/server/fmgr.h:585:26: note: in definition of macro ‘DirectFunctionCall1’
  DirectFunctionCall1Coll(func, InvalidOid, arg1)
                          ^~~~
hll.c:1492:36: note: each undeclared identifier is reported only once for each function it appears in
     Datum dd = DirectFunctionCall1(byteain, PG_GETARG_DATUM(0));
                                    ^
/usr/local/pgsql/include/server/fmgr.h:585:26: note: in definition of macro ‘DirectFunctionCall1’
  DirectFunctionCall1Coll(func, InvalidOid, arg1)
                          ^~~~
hll.c: In function ‘hll_out’:
hll.c:1534:36: error: ‘byteaout’ undeclared (first use in this function)
     Datum dd = DirectFunctionCall1(byteaout, PG_GETARG_DATUM(0));
                                    ^
/usr/local/pgsql/include/server/fmgr.h:585:26: note: in definition of macro ‘DirectFunctionCall1’
  DirectFunctionCall1Coll(func, InvalidOid, arg1)
                          ^~~~
hll.c: In function ‘hll_hashval_in’:
hll.c:1581:36: error: ‘int8in’ undeclared (first use in this function)
     Datum dd = DirectFunctionCall1(int8in, PG_GETARG_DATUM(0));
                                    ^
/usr/local/pgsql/include/server/fmgr.h:585:26: note: in definition of macro ‘DirectFunctionCall1’
  DirectFunctionCall1Coll(func, InvalidOid, arg1)
                          ^~~~
hll.c: In function ‘hll_hashval_out’:
hll.c:1590:36: error: ‘int8out’ undeclared (first use in this function)
     Datum dd = DirectFunctionCall1(int8out, PG_GETARG_DATUM(0));
                                    ^
/usr/local/pgsql/include/server/fmgr.h:585:26: note: in definition of macro ‘DirectFunctionCall1’
  DirectFunctionCall1Coll(func, InvalidOid, arg1)
                          ^~~~
hll.c: In function ‘hll_recv’:
hll.c:3343:36: error: ‘bytearecv’ undeclared (first use in this function)
     Datum dd = DirectFunctionCall1(bytearecv, PG_GETARG_DATUM(0));
                                    ^
/usr/local/pgsql/include/server/fmgr.h:585:26: note: in definition of macro ‘DirectFunctionCall1’
  DirectFunctionCall1Coll(func, InvalidOid, arg1)
                          ^~~~
<builtin>: recipe for target 'hll.o' failed
make: *** [hll.o] Error 1

My pg_config:

$ pg_config
BINDIR = /usr/local/pgsql/bin
DOCDIR = /usr/local/pgsql/share/doc
HTMLDIR = /usr/local/pgsql/share/doc
INCLUDEDIR = /usr/local/pgsql/include
PKGINCLUDEDIR = /usr/local/pgsql/include
INCLUDEDIR-SERVER = /usr/local/pgsql/include/server
LIBDIR = /usr/local/pgsql/lib
PKGLIBDIR = /usr/local/pgsql/lib
LOCALEDIR = /usr/local/pgsql/share/locale
MANDIR = /usr/local/pgsql/share/man
SHAREDIR = /usr/local/pgsql/share
SYSCONFDIR = /usr/local/pgsql/etc
PGXS = /usr/local/pgsql/lib/pgxs/src/makefiles/pgxs.mk
CONFIGURE = '--with-systemd' '--with-icu' '--with-uuid=ossp' '--with-libxml' '--with-libxslt' '--with-wal-segsize=64'
CC = gcc
CPPFLAGS = -DFRONTEND -D_GNU_SOURCE -I/usr/include/libxml2
CFLAGS = -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2
CFLAGS_SL = -fpic
LDFLAGS = -L../../src/common -Wl,--as-needed -Wl,-rpath,'/usr/local/pgsql/lib',--enable-new-dtags
LDFLAGS_EX =
LDFLAGS_SL =
LIBS = -lpgcommon -lpgport -lpthread -lxslt -lxml2 -lz -lreadline -lrt -lcrypt -ldl -lm
VERSION = PostgreSQL 10devel

Thanks in advance!

Debian packages

Debian packages to install this as an extension would make it very convenient to use.

Cardinality of hello world example (explicit set of 3) is wrong

--- Make a dummy table
CREATE TABLE helloworld (
        id              integer,
        set     hll
);

--- Insert an empty HLL
INSERT INTO helloworld(id, set) VALUES (1, hll_empty());

--- Add a hashed integer to the HLL
UPDATE helloworld SET set = hll_add(set, hll_hash_integer(12345)) WHERE id = 1;

--- Or add a hashed string to the HLL
UPDATE helloworld SET set = hll_add(set, hll_hash_text('hello world')) WHERE id = 1;

--- Get the cardinality of the HLL
SELECT hll_cardinality(set) FROM helloworld WHERE id = 1;
---  hll_cardinality 
--- -----------------
---                2
--- (1 row)

Hex is \x128b7faaebcf97601e5541533f6046eb7f610e which if I'm reading it right is the explicit layout so I'd expect the count to be exact. Loading that hex up in js-hll gives the expected cardinality of 3.

Compile on OS X

This doesn't compile on OS X (10.8) because byteswap.h doesn't exist on OS X. As far as I can tell it's included simply for bswap_64. It looks like an equivalent method exists, OSSwapInt64, in libkern.

Looks like this might do the trick:

#if defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#define bswap_64 OSSwapInt64
#else
#include <byteswap.h>
#endif

Also, there's a compiler flag bug:

cc -I/usr/local/Cellar/ossp-uuid/1.6.2/include -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv  -fPIC -std=c99 -I. -I. -I/usr/local/Cellar/postgresql/9.2.1/include/server -I/usr/local/Cellar/postgresql/9.2.1/include/internal -I/usr/include/libxml2   -c -o hll.o hll.c
c++  -fPIC -std=c99 -I. -I. -I/usr/local/Cellar/postgresql/9.2.1/include/server -I/usr/local/Cellar/postgresql/9.2.1/include/internal -I/usr/include/libxml2   -c -o MurmurHash3.o MurmurHash3.cpp
error: invalid argument '-std=c99' not allowed with 'C++/ObjC++'

Looks like Apple's clang doesn't like -std=c99 being passed to c++. For reference, the version numbers for my clang are below:

[ [email protected] ] [ postgresql-hll ]
$> cc --version
Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin12.2.0
Thread model: posix
[ [email protected] ] [ postgresql-hll ]
$> c++ --version
Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin12.2.0
Thread model: posix

Valgrind warnings

Hello

I have a loop that inserts 4 byte values into a HLL. It hits a Valgrind warning

With these parameters:

Log2m = 11;
Regwidth = 5;
Expthresh = -1;
Sparseon = 1;

it happens after inserting 160 elements.

It seems as if multiset_packed_size computes a too-small size for the packed buffer that has to be used.

Valgrind warnings look as follows. Line numbers are off because I've been playing with this part of the code outside Postgres.

==29406== Invalid read of size 8
==29406== at 0x40B2D2: bitstream_pack (byteswap.h:111)
==29406== by 0x40BBD8: multiset_pack (hll.c:245)
==29406== Address 0x548e387 is 311 bytes inside a block of size 317 alloc'd

==29406== Invalid write of size 8
==29406== at 0x40B2E4: bitstream_pack (hll.c:155)
==29406== by 0x40BBD8: multiset_pack (hll.c:245)
==29406== Address 0x548e387 is 311 bytes inside a block of size 317 alloc'd

which is this line: * (uint64_t *) bwcp->bwc_curp = qw;

Hopefully this is enough info to find the bug, otherwise I can dig more. I'm reasonably sure you can reproduce this with HLL running inside Postgres, but it's harder to Valgrind there.

I can also build a test against the original HLL source if that will help you.

Cheers

Albert

how to accelerate count(*) top 10 question

hll solve count distint question,but how to accelerate quesiton like
select id,count(*) from test group by id order by 2 limit 10;
table test have more 1 billion data.

hll_hash_any --> hll_hash

Timon,

I'd like to map hll_hash_any to simply hll_hash. It's just a name thing; the new function would do exactly the same thing. We'd have to keep the old name for backwards compat, of course.

Implement hll_hash_date

While hll_hash_timestamptz wouldn't be terribly useful, hll_hash_date certainly could be. And it shouldn't be hard to implement; you can transform a date to an INT. However, since the range of INTs for a valid date would be different from 0-MAXINT, should we adjust the hash function somehow?

make hll_add_agg parallel safe

Is it possible to make hll_add_agg() and other functions in this package parallel safe?
I see that postgres doesn't try to start background workers once it sees hll_add_agg() function.
This limitation means that every time we need to aggregate hll, we are limited to a single process.

I tried it on Postgres 10.5.

Hll as primary key?

This is more like a feature request: We were thinking of using hll-shards as primary keys in our database. This would allow keeping a relational structure based on probabilistic id abstraction, an interesting area of study for privacy aware data handling.

Currently, the hll-type has no default operator class defined, which results in the following error of one wants to use hll as a primary key:

ERROR:  data type hll has no default operator class for access method "btree"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.
SQL state: 42704

Could someone point me in the right direction to use hll-shards as primary key in Postgres? Perhaps I could use the default operator class from bytea, but how is this done?

Why hll_add_agg not work as exepcted?

Hi All,

I am new for this library, I tried almostly the exactly same example, but it did not work at my side -
select statis_date, hll_add_agg(hll_hash_text(member_id)) from tb_member_order_shard group by 1;

During trail and error, I found the following interesting thing - The only difference btwn 'Work' and 'NOT Work' is - the former has 'limit 10', otherwise, the error msg prompted the function is not supported.

Work -
select hll_add_agg(a) from (select hll_hash_text(member_id) as a from tb_member_order_shard **limit 10**) b;

NOT Work
select hll_add_agg(a) from (select hll_hash_text(member_id) as a from tb_member_order_shard) b;

Error:

An error occurred when executing the SQL command:
select hll_add_agg(a) from (select hll_hash_text(member_id) as a from tb_member_order_shard) b

ERROR: unsupported aggregate function hll_add_agg

The PG version: PostgreSQL 10.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16), 64-bit

The columns of interest in the table 'tb_member_order_shard' -
statis_date | text |
member_id | text |

Error in installing postgresql-hll

I am new to Postgresql . I am trying to install this extension -

I have updated my PG_CONFIG to correct pg_config location-
find / -name "pg_config"
/usr/bin/pg_config

But whenever I am trying to create tarballl -

tar cvfz postgresql${PGSHRT}-hll-${VER}.tar.gz postgresql-hll \ --transform="s/postgresql-hll/postgresql${PGSHRT}-hll/g"
tar: postgresql-hll: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

I tried to install from debian package - http://packages.ubuntu.com/trusty/amd64/postgresql-hll/download
but it also does not help.

I have postgres 9.3 installed . Can some one help me to correctly install this extension.

Support for adding pre-computed HLL entries into an HLL table

I have developed a framework that periodically produces several HLL entries using the java-hll library, and am looking for a way to insert them directly into a Postgres table so as to keep a running total, etc.

The java-hll library README has the following entry, but I am unsure how to take the generated hex output and insert it into an existing table:

"Writing an HLL to its hex representation of storage specification, v1.0.0 (for example, to be inserted into a PostgreSQL database):

final byte[] bytes = hll.toBytes();
final String output = "\\x" + NumberUtil.toHex(bytes, 0, bytes.length)

"

Any advise on how to leverage both of these technologies would be greatly appreciated, as it seems that the additive nature of the data structure makes this scenario seem plausible.

Getting ERROR: explicit multiset too large

Hello, I am getting this error when trying to insert HLL's into the DB which seems to break this constraint:
https://github.com/citusdata/postgresql-hll/blob/master/src/hll.c#L554
I am trying to insert millions of id's into the HLL with value for log2m=20 and regWidth=7. This does not cause a problem in java-hll library, but when inserting the HLL into the DB it fails.

The value for MS_MAXDATA seems to be too low for practical purposes. I was wondering what the rationale behind this limit is.

"Add hll to shared_preload_libraries" needs documentation

Release 2.13 adds the requirement that hll is loaded via shared_preload_libraries, but this is not documented.

Please also add a rationale why this was changed. So far hll was "just" a datatype, and the fact a datatype needs to be preloaded is pretty surprising, and likely adds considerable push back on the adoption of this extension. (I see a planner hook in the code, is that really necessary?)

lstdc++ in Makefile

I'm able to build, install and run postgresql-hll without using lstdc++ in Makefile. Is there any reason why this line is included in Makefile?

SHLIB_LINK += -lstdc++

Frequent HLL bitstream_unpack crashes

We’ve been seeing nearly daily crashes from a PostgreSQL 9.6 application that is heavily
dependent on the HLL extension (v 2.10.2). All these crashes are from inside the HLL
bitstream_unpack function. Usually they’re from an INSERT VALUES statement, but
occasionally they are from an hll_cardinality call in a query. The format of the HLL cells
is always set using expressions like: hll_empty(17,5,-1,1) || hll_hash_bigint(879826435) || ...

I think I’ve identified the root cause, but I’d like someone who is familiar with the code
in the HLL library to confirm my hypothesis:

In bitstream_unpack it pulls a full quadword of data out of the bitstream using the 
brc_curp pointer.  Usually this is not a problem.  However, if the brc_curp pointer is 
less than 8 bytes from the end of the bitstream data, then that quadword read is 
reading past the end of the actual bitstream data.  Because of the subsequent bit
reordering, shifting, and masking this has no effect of the answers.  However, when
the end of the bitstream is very close to the end of an OS page then the quadword
read will attempt to read the next OS page, and if that next OS page does not exist
in this process, then it will SEGV.

Assuming I’ve correctly identified the problem, the attached patch should fix the issue.

Regards,
Steve Kirk

hll_2_10_2_patch.txt

BTW, The crash stacks all look roughly like:

#0 bitstream_unpack (brcp=brcp@entry=0x7ffc69814290) at hll.c:263
#1 0x0000147cbfcbe8ac in sparse_unpack (i_size=, i_bitp=0x7ffc69814327 "", i_nfilled=10403, i_log2nregs=, i_width=5, i_regp=0x7ffc69814320 "\002") at hll.c:359
#2 multiset_unpack (o_msp=o_msp@entry=0x7ffc698142f0, i_bitp=i_bitp@entry=0x147a16bf903c "\023\221\177", i_size=, o_encoded_type=o_encoded_type@entry=0x0) at hll.c:1188
#3 0x0000147cbfcc0823 in hll_union (fcinfo=) at hll.c:2042
#4 0x0000000000617132 in ExecMakeFunctionResultNoSets (fcache=0x147cbb3eb948, econtext=0x147a1d6cd530, isNull=0x147a1d6ce09d "", isDone=) at execQual.c:2041
#5 0x000000000061cace in ExecTargetList (tupdesc=, isDone=0x0, itemIsDone=0x147a1d6cffa0, isnull=0x147a1d6ce090 "", values=0x147a1d6ce000, econtext=0x147a1d6cd530, targetlist=0x147cbb3ecc28) at execQual.c:5423
#6 ExecProject (projInfo=, isDone=isDone@entry=0x0) at execQual.c:5647
#7 0x000000000062f10b in ExecOnConflictUpdate (returning=, canSetTag=1 '\001', estate=0x147a1d6c8038, excludedSlot=0x147a1d6c9bc0, planSlot=0x147a1d6c9bc0, conflictTid=0x7ffc69854520, resultRelInfo=0x147a1d6c81c8, mtstate=0x147a1d6c82d8) at nodeModifyTable.c:1234
#8 ExecInsert (canSetTag=1 '\001', estate=0x147a1d6c8038, onconflict=ONCONFLICT_UPDATE, arbiterIndexes=0x147a1654fd28, planSlot=0x147a1d6c9bc0, slot=0x147a1d6c9bc0, mtstate=0x147a1d6c82d8) at nodeModifyTable.c:410
#9 ExecModifyTable (node=node@entry=0x147a1d6c82d8) at nodeModifyTable.c:1512
#10 0x00000000006162a8 in ExecProcNode (node=node@entry=0x147a1d6c82d8) at execProcnode.c:396
#11 0x0000000000612727 in ExecutePlan (dest=0x147a1654d888, direction=, numberTuples=0, sendTuples=, operation=CMD_INSERT, use_parallel_mode=, planstate=0x147a1d6c82d8, estate=0x147a1d6c8038) at execMain.c:1567
#12 standard_ExecutorRun (queryDesc=0x147cbb3c6438, direction=, count=0) at execMain.c:339

Why hll_add_agg not work as exepcted?

Hi All,

I am new for this library, I tried almostly the exactly same example, but it did not work at my side -
select statis_date, hll_add_agg(hll_hash_text(member_id)) from tb_member_order_shard group by 1;

During trail and error, I found the following interesting thing - The only difference btwn 'Work' and 'NOT Work' is - the former has 'limit 10', otherwise, the error msg prompted the function is not supported.

Work -
select hll_add_agg(a) from (select hll_hash_text(member_id) as a from tb_member_order_shard **limit 10**) b;

NOT Work
select hll_add_agg(a) from (select hll_hash_text(member_id) as a from tb_member_order_shard) b;

Error:

An error occurred when executing the SQL command:
select hll_add_agg(a) from (select hll_hash_text(member_id) as a from tb_member_order_shard) b

ERROR: unsupported aggregate function hll_add_agg

The PG version: PostgreSQL 10.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16), 64-bit

The columns of interest in the table 'tb_member_order_shard' -
statis_date | text |
member_id | text |

support 9.4

is there any easy way to support 9.4 without any version mismatch error

Regression tests fail with PostgreSQL 10

PG 10's \d command displays more informational columns per table column. This causes the typmod test to fail:

--- typmod.ref	2018-04-06 17:15:13.120975855 +0200
+++ typmod.out	2018-04-07 13:53:14.916061671 +0200
@@ -13,10 +13,10 @@
 CREATE TABLE test_qiundgkm (v1 hll);
 CREATE TABLE
 \d test_qiundgkm
-Table "public.test_qiundgkm"
- Column | Type | Modifiers 
---------+------+-----------
- v1     | hll  | 
+          Table "public.test_qiundgkm"
+ Column | Type | Collation | Nullable | Default 
+--------+------+-----------+----------+---------
+ v1     | hll  |           |          | 

Generally I'd suggest moving to standard pg_regress for testing. It supports multiple expected output files (expected/typmod.out, expected/typmod_1.out, ...) so this problem could easily be worked around.

(Problem discovered while updating the postgresql-hll package for Debian and apt.postgresql.org.)

PostgreSQL 11 build error

Hi,

hll fails against PostgreSQL 11:

/usr/lib64/ccache/clang -xc++ -Wno-ignored-attributes -fno-strict-aliasing -fwrapv -O2 -fPIC -I. -I./ -I/usr/pgsql-11/include/server -I/usr/pgsql-11/include/internal -D_GNU_SOURCE -I/usr/include/libxml2 -I/usr/include -flto=thin -emit-llvm -c -o MurmurHash3.bc MurmurHash3.cpp hll.c: In function 'setup_multiset': hll.c:2760:64: error: macro "AllocSetContextCreate" passed 5 arguments, but takes just 3 ALLOCSET_DEFAULT_MAXSIZE); ^ hll.c:2756:18: error: 'AllocSetContextCreate' undeclared (first use in this function); did you mean 'SlabContextCreate'? tmpcontext = AllocSetContextCreate(rcontext, ^~~~~~~~~~~~~~~~~~~~~ SlabContextCreate hll.c:2756:18: note: each undeclared identifier is reported only once for each function it appears in make[1]: *** [<builtin>: hll.o] Error 1 make[1]: *** Waiting for unfinished jobs.... hll.c:2759:40: error: too many arguments provided to function-like macro invocation ALLOCSET_DEFAULT_INITSIZE, ^ /usr/pgsql-11/include/server/utils/memutils.h:165:9: note: macro 'AllocSetContextCreate' defined here #define AllocSetContextCreate(parent, name, allocparams) \ ^ hll.c:2756:18: error: use of undeclared identifier 'AllocSetContextCreate' tmpcontext = AllocSetContextCreate(rcontext, ^ 2 errors generated. make[1]: *** [/usr/pgsql-11/lib/pgxs/src/makefiles/../../src/Makefile.global:1009: hll.bc] Error 1 make[1]: Leaving directory '/home/devrim/Documents/Devrim/Projects/repo/pgrpms/rpm/redhat/master/hll/master/postgresql-hll-2.10.2' error: Bad exit status from /var/tmp/rpm-tmp.qcj6ua (%build)

Regards, Devrim

Unable to install postgres-hll on Ubuntu

I am encountering some issues when trying to follow the instructions for installing the postgresql-hll extension.

I have downloaded the v2.12 release and unzipped. On trying to follow the instructions to compile I am getting the following message.

cd postgresql-hll
~/postgresql-hll$ PG_CONFIG=/usr/bin/pg_config make
Makefile:29: /usr/lib/postgresql/11/lib/pgxs/src/makefiles/pgxs.mk: No such file
or directory
make: *** No rule to make target '/usr/lib/postgresql/11/lib/pgxs/src/makefiles/pgxs.mk'. Stop.

uname -a

Linux ip-172-30-1-137 4.15.0-1035-aws #37-Ubuntu SMP Mon Mar 18 16:15:14 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

How can I correct this and get a working installation?

  1. I have also attempted to install using sudo apt install postgresql-hll but the installation places files in directories for the wrong version.

  2. rpmbuild also fails because of a missing spec file.

PostgreSQL 11 build issue

Hi,
I'm getting this on my Fedora 28 box, against PostgreSQL 11:
`

  • /usr/bin/make -j4
    hll.c: In function 'setup_multiset':
    hll.c:2760:64: error: macro "AllocSetContextCreate" passed 5 arguments, but takes just 3
    ALLOCSET_DEFAULT_MAXSIZE);
    ^
    hll.c:2756:18: error: 'AllocSetContextCreate' undeclared (first use in this function); did you mean 'SlabContextCreate'?
    tmpcontext = AllocSetContextCreate(rcontext,
    ^~~~~~~~~~~~~~~~~~~~~
    SlabContextCreate
    hll.c:2756:18: note: each undeclared identifier is reported only once for each function it appears in
    make[1]: *** [: hll.o] Error 1
    make[1]: *** Waiting for unfinished jobs....
    hll.c:2759:40: error: too many arguments provided to function-like macro invocation
    ALLOCSET_DEFAULT_INITSIZE,
    ^
    /usr/pgsql-11/include/server/utils/memutils.h:165:9: note: macro 'AllocSetContextCreate' defined here
    #define AllocSetContextCreate(parent, name, allocparams)
    ^
    hll.c:2756:18: error: use of undeclared identifier 'AllocSetContextCreate'
    tmpcontext = AllocSetContextCreate(rcontext,
    ^
    2 errors generated.
    make[1]: *** [/usr/pgsql-11/lib/pgxs/src/makefiles/../../src/Makefile.global:1009: hll.bc] Error 1
    error: Bad exit status from /var/tmp/rpm-tmp.0j1PDS (%build)
    Bad exit status from /var/tmp/rpm-tmp.0j1PDS (%build)
    rpmsign: no arguments given
    make: *** [../../../common/Makefile.global-PG11:28: build11] Error 1`

Can you please take a look?

Regards, Devrim

hll_add multiple values

Hi everyone,

Is it possible to add multiple values to HLL at once? Here is example from README for on element:

UPDATE helloworld SET set = hll_add(set, hll_hash_integer(12345)) WHERE id = 1;

What is the most efficient way to add multiple values (I will be adding about ~50 elements for one operation)?

"could not identify an equality operator for type hll" in GROUP BY

When I use a column with hll type as a field in GROUP BY clause, I get the error:

ERROR:  could not identify an equality operator for type hll

Here's a small repro:

CREATE TABLE tmp (int num, set hll);
INSERT INTO tmp VALUES (1, hll_empty());
INSERT INTO tmp VALUES (2, hll_empty());
INSERT INTO tmp VALUES (3, hll_empty());
INSERT INTO tmp VALUES (4, hll_empty());
SELECT SUM(num), set FROM tmp GROUP BY set;

While I expect it to result in a row consisting of 10 and empty hll value, I get the error above.

postgresql-hll Version: master (77aa0fe)
PostgreSQL Version: 11.5
OS Version: Debian 10

effective MAX regwidth is inconsistent with storage spec and java-hll

The storage spec & postgresql-hll docs say...

https://github.com/aggregateknowledge/hll-storage-spec/blob/v1.0.0/STORAGE.md

registerWidth may take values from 1 to 8, inclusive, ...
https://github.com/aggregateknowledge/postgresql-hll/blob/master/README.markdown#explanation-of-parameters-and-tuning
The number of bits used per register in the HyperLogLog algorithm. Must be at least 1 and at most 8

My C is a bit rusty, so i may be missing something, but based on skimming the code, the effective MAX regwidth thta can be used in postgresql-hll is actually 7 -- and that seems to be supported by the error message string in the code...

#define REGWIDTH_BITS 3
...
#define MAX_BITVAL(nbits) ((1 << nbits) - 1)
...
if (regwidth < 0 || regwidth > MAX_BITVAL(REGWIDTH_BITS))
    ereport(ERROR,
            (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
             errmsg("regwidth modifier must be between 0 and 7")));

New release for v12 support

Hi,

I just noticed that v12 support is committed already. When will you release a new version for v12?

Thanks!

Regards, Devrim

hardcoded pg_config location

The hardcoded pg_config location

PG_CONFIG = /usr/pgsql-9.1/bin/pg_config

will obviously only work on a very particular installation.

I suggest that you change that line to

PG_CONFIG = pg_config

so that your package can build on other people's machines out of the box. That's how most/all other extension packages do it.

add hll_cardinality_agg()

I think this wrapper function should be part of the standard HLL library, for doing ad-hoc cardinality estimates. It would be a wrapper for:

hll_cardinality(hll_add_agg(hll_hash_any(VALUE)))

Problem with log2m >= 18

Great extension, thanks for making it open-source.

I came across with this issue while playing around with it:

When I use bigger values than 18 for log2m parameter in hll_add_agg function it crashes. Here is how to replicate problem:
I tried this on PostgreSQL 9.2.4

-- First create dataset:
wget http://examples.citusdata.com/tpch_2_13_0.tar.gz
tar xvfz tpch_2_13_0.tar.gz
cd tpch_2_13_0
gmake

./dbgen -f -s 1 -T L

-- Create table and load data
CREATE TABLE LINEITEM
(
l_orderkey BIGINT not null,
l_partkey INTEGER not null,
l_suppkey INTEGER not null,
l_linenumber INTEGER not null,
l_quantity DECIMAL(15,2) not null,
l_extendedprice DECIMAL(15,2) not null,
l_discount DECIMAL(15,2) not null,
l_tax DECIMAL(15,2) not null,
l_returnflag CHAR(1) not null,
l_linestatus CHAR(1) not null,
l_shipdate DATE not null,
l_commitdate DATE not null,
l_receiptdate DATE not null,
l_shipinstruct CHAR(25) not null,
l_shipmode CHAR(10) not null,
l_comment VARCHAR(44) not null
);

COPY lineitem FROM 'YOUR_PATH/tpch_2_13_0/lineitem.tbl' WITH DELIMITER '|';

-- This query works without a problem:
SELECT
hll_cardinality(hll_add_agg(hll_hash_bigint(l_orderkey, 0), 17))
FROM
lineitem;

-- This query crashes:
SELECT
hll_cardinality(hll_add_agg(hll_hash_bigint(l_orderkey, 0), 18))
FROM
lineitem;

For some inputs hll_cardinality function returns negative results.

For some inputs hll_cardinality function returns negative results. It is caused by invalid multiplication of uint64_t with -1.

Example:

select public.hll_cardinality( decode( '14887fc63f9d735adef38d7779ce7dace3bcd67b9ee319df73fdf339d777dee75ae6bbbc6759deb3bdeb5ace7bcc673bce718debbbceb5bd775bc6bfdd6f39eeb39debbec671ce6b9ec735acf35ad735acf3bbd6b99d637bfeb7aeef99d6739d7fbacef5ad7399e7738d6f5ed6f9bc6b5bceb3edeb7bdef5ac67d8e6f7bdef3afe759cff59ef39ac6f9ecef59c6b5ac6f3cc63bee6f39d6b3ae677cd677cd6b58ef3fa', 'hex')::hll ) ;

result before fix: -7.01470685321371e+17
result after fix: 10452727910.4903

15/33 Regression Tests Fail on 9.4

Perhaps I have a misconfiguration locally, but while many of the HLL functions work while I'm toying with them manually, the regression tests have many failures.

The failures seem primarily to do with murmur hash algorithm. Maybe this just changed slightly in 9.4? Also any of the union and some of the sparse tests seem to also fail. I presume for the same reason.

Here is my output:

lepton:regress gavin$ DEBUG=1 make clean && make -j5
rm -f binary.dat *.out *.diff
add_aggagg_oobauto_sparsecard_opcast_shape .. PASS
 .. PASS
 .. PASS
copy_binarycumulative_add_cardinality_correctioncumulative_add_comprehensive_promotion .. PASS
cumulative_add_sparse_edge .. PASS
cumulative_add_sparse_random .. FAIL
cumulative_add_sparse_step .. FAIL
cumulative_union_comprehensive .. FAIL
cumulative_union_explicit_explicit .. FAIL
cumulative_union_explicit_promotion .. FAIL
cumulative_union_probabilistic_probabilistic .. FAIL
cumulative_union_sparse_full_representation .. FAIL
cumulative_union_sparse_promotion .. FAIL
cumulative_union_sparse_sparse .. FAIL
equal .. PASS
explicit_thresh .. PASS
hash .. PASS
hash_any .. PASS
meta_func .. PASS
murmur_bigint .. FAIL
murmur_bytea .. FAIL
nosparse .. PASS
notequal .. PASS
scalar_oob .. PASS
storedproc .. PASS
transaction .. PASS
typmod .. PASS
typmod_insert .. PASS
union_op .. PASS
 .. FAIL
 .. FAIL
 .. FAIL
 .. FAIL
ERROR: 15 / 33 tests failed

--- copy_binary.ref 2015-02-05 13:14:10.000000000 -0800
+++ copy_binary.out 2015-02-05 13:51:11.000000000 -0800
@@ -17,6 +17,7 @@
 (1 row)

 \COPY test_binary TO 'binary.dat' WITH (FORMAT "binary")
+COPY 1
 DELETE FROM test_binary;
 DELETE 1
 SELECT hll_cardinality(v1) FROM test_binary;
@@ -25,6 +26,7 @@
 (0 rows)

 \COPY test_binary FROM 'binary.dat' WITH (FORMAT "binary")
+COPY 1
 SELECT hll_cardinality(v1) FROM test_binary;
  hll_cardinality 
 -----------------
--- cumulative_add_cardinality_correction.ref   2015-02-05 13:14:10.000000000 -0800
+++ cumulative_add_cardinality_correction.out   2015-02-05 13:51:12.000000000 -0800
@@ -28,6 +28,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_msgfjqhm (cardinality, raw_value, union_compressed_multiset) from pstdin with csv header
+COPY 6144
 SELECT COUNT(*) FROM test_msgfjqhm;
  count 
 -------
--- cumulative_add_comprehensive_promotion.ref  2015-02-05 13:14:10.000000000 -0800
+++ cumulative_add_comprehensive_promotion.out  2015-02-05 13:51:13.000000000 -0800
@@ -28,6 +28,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_ptwysrqk (cardinality, raw_value, union_compressed_multiset) from pstdin with csv header
+COPY 10001
 SELECT COUNT(*) FROM test_ptwysrqk;
  count 
 -------
--- cumulative_add_sparse_edge.ref  2015-02-05 13:14:10.000000000 -0800
+++ cumulative_add_sparse_edge.out  2015-02-05 13:51:11.000000000 -0800
@@ -28,6 +28,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_eopzdzwz (cardinality, raw_value, union_compressed_multiset) from pstdin with csv header
+COPY 515
 SELECT COUNT(*) FROM test_eopzdzwz;
  count 
 -------
--- cumulative_add_sparse_random.ref    2015-02-05 13:14:10.000000000 -0800
+++ cumulative_add_sparse_random.out    2015-02-05 13:51:11.000000000 -0800
@@ -19,6 +19,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_beelewuo (cardinality, raw_value, union_compressed_multiset) from pstdin with csv header
+COPY 513
 SELECT COUNT(*) FROM test_beelewuo;
  count 
 -------
--- cumulative_add_sparse_step.ref  2015-02-05 13:14:10.000000000 -0800
+++ cumulative_add_sparse_step.out  2015-02-05 13:51:11.000000000 -0800
@@ -19,6 +19,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_lunfjncl (cardinality, raw_value, union_compressed_multiset)  from pstdin with csv header
+COPY 513
 SELECT COUNT(*) FROM test_lunfjncl;
  count 
 -------
--- cumulative_union_comprehensive.ref  2015-02-05 13:14:10.000000000 -0800
+++ cumulative_union_comprehensive.out  2015-02-05 13:51:15.000000000 -0800
@@ -19,6 +19,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_rhswkjtc (cardinality,compressed_multiset,union_cardinality,union_compressed_multiset) from pstdin with csv header
+COPY 1001
 SELECT COUNT(*) FROM test_rhswkjtc;
  count 
 -------
--- cumulative_union_explicit_explicit.ref  2015-02-05 13:14:10.000000000 -0800
+++ cumulative_union_explicit_explicit.out  2015-02-05 13:51:12.000000000 -0800
@@ -19,6 +19,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_swlnhisq (cardinality,compressed_multiset,union_cardinality,union_compressed_multiset) from pstdin with csv header
+COPY 257
 SELECT COUNT(*) FROM test_swlnhisq;
  count 
 -------
--- cumulative_union_explicit_promotion.ref 2015-02-05 13:14:10.000000000 -0800
+++ cumulative_union_explicit_promotion.out 2015-02-05 13:51:12.000000000 -0800
@@ -28,6 +28,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_wsdiietv (cardinality,compressed_multiset,union_cardinality,union_compressed_multiset) from pstdin with csv header
+COPY 629
 SELECT COUNT(*) FROM test_wsdiietv;
  count 
 -------
--- cumulative_union_probabilistic_probabilistic.ref    2015-02-05 13:14:10.000000000 -0800
+++ cumulative_union_probabilistic_probabilistic.out    2015-02-05 13:51:22.000000000 -0800
@@ -19,6 +19,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_mpuahgwy (cardinality,compressed_multiset,union_cardinality,union_compressed_multiset) from pstdin with csv header
+COPY 1001
 SELECT COUNT(*) FROM test_mpuahgwy;
  count 
 -------
--- cumulative_union_sparse_full_representation.ref 2015-02-05 13:14:10.000000000 -0800
+++ cumulative_union_sparse_full_representation.out 2015-02-05 13:51:12.000000000 -0800
@@ -28,6 +28,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_tagumlbl (cardinality,compressed_multiset,union_cardinality,union_compressed_multiset) from pstdin with csv header
+COPY 4
 SELECT COUNT(*) FROM test_tagumlbl;
  count 
 -------
--- cumulative_union_sparse_promotion.ref   2015-02-05 13:14:10.000000000 -0800
+++ cumulative_union_sparse_promotion.out   2015-02-05 13:51:20.000000000 -0800
@@ -28,6 +28,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_bsnvqefe (cardinality,compressed_multiset,union_cardinality,union_compressed_multiset) from pstdin with csv header
+COPY 1513
 SELECT COUNT(*) FROM test_bsnvqefe;
  count 
 -------
--- cumulative_union_sparse_sparse.ref  2015-02-05 13:14:10.000000000 -0800
+++ cumulative_union_sparse_sparse.out  2015-02-05 13:51:13.000000000 -0800
@@ -19,6 +19,7 @@
 -- Copy the CSV data into the table
 --
 \copy test_bmbffonl (cardinality,compressed_multiset,union_cardinality,union_compressed_multiset) from pstdin with csv header
+COPY 513
 SELECT COUNT(*) FROM test_bmbffonl;
  count 
 -------
--- murmur_bigint.ref   2015-02-05 13:14:10.000000000 -0800
+++ murmur_bigint.out   2015-02-05 13:51:13.000000000 -0800
@@ -17,6 +17,7 @@
 );
 CREATE TABLE
 \copy test_seznjqbb (seed, pre_hash_long, post_hash_long) from pstdin with csv header
+COPY 600
 SELECT COUNT(*) FROM test_seznjqbb;
  count 
 -------
--- murmur_bytea.ref    2015-02-05 13:14:10.000000000 -0800
+++ murmur_bytea.out    2015-02-05 13:51:13.000000000 -0800
@@ -17,6 +17,7 @@
 );
 CREATE TABLE
 \copy test_qfwzdmoy (seed, pre_hash_long, post_hash_long) from pstdin with csv header
+COPY 600
 SELECT COUNT(*) FROM test_qfwzdmoy;
  count 
 -------
make: *** [all] Error 1

Cardinality is coming off by 2 percent (o_log2m=17, o_regwidth=5, o_expthresh=-1,o_sparseon=1)

We are using HLL for calculating unique users in our system, for a day or date range depending on requirement. It worked fine with error percentage of 0.025 to 0.9% (acceptable for our use case), but last week's data is going off by 2%.
Following are the details:
Parameters: o_log2m=17, o_regwidth=5, o_expthresh=-1,o_sparseon=1
Data: User Ids of UUID type, generated by backend written in Golang
Unique count: 328428
Cardinality by HLL: 335881
For one particular day its coming off by 7000(approx)
user count issue

As you can see from graph, for particular day (14 Sept) unique user for day are going more than total users of the day.

I am attaching CSV file which has list of unique user_ids and total count from our DB table, and we are able to recreate this issue in table(user_debug(id serial, user_id varchar, count int)) created from this CSV.

Query: select count(distinct(user_id)) as user from user_debug;
O/p: 328428

Query: select hll_cardinality(hll_add_agg(hll_hash_text(user_id))) from user_debug;
O/p: 335881

We tried to calculate cardinality per distinct 100000 user_ids in table and results is off by 150-400 by HLL, same goes with range of 150000 distict user_ids.
So we tried to run on different subset of rows and recreated issue with below query:
with a as ((select distinct(user_id) as user from user_debug limit 160000 offset 0) UNION (select distinct(user_id) as user from user_debug limit 160000 offset 168248 ))
select hll_cardinality(hll_add_agg(hll_hash_text(a.user))) from a;
This should have returned close to 320000 as count, but its returning 328345.
We couldn't debug any further, can you check?
CSV is attached.

user_id.csv.zip

How to build it into greenplum 5.0?

We build hll into greenplum 5.0, but got an error,somethings like implict declaration of 'array_contains_nulls'.Does greenplum version not match ?

compile

In order to compile I had to

include "utils/int8.h"

in hll.c

Platform: debian / postgresql-9.2.2 / gcc-4.7

11/33 regression tests failed on pg 9.3.6 on osx mavericks. (All tests passed on ubuntu with similar setup)

Following the installation instructions on a clean pg 9.3.6 build gives: ERROR: 11 / 33 tests failed. Is this a known issue?

%% make
add_agg .. PASS
agg_oob .. PASS
auto_sparse .. PASS
card_op .. PASS
cast_shape .. PASS
copy_binary .. PASS
cumulative_add_cardinality_correction .. FAIL
cumulative_add_comprehensive_promotion .. FAIL
cumulative_add_sparse_edge .. FAIL
cumulative_add_sparse_random .. FAIL
cumulative_add_sparse_step .. FAIL
cumulative_union_comprehensive .. FAIL
cumulative_union_explicit_explicit .. PASS
cumulative_union_explicit_promotion .. FAIL
cumulative_union_probabilistic_probabilistic .. FAIL
cumulative_union_sparse_full_representation .. FAIL
cumulative_union_sparse_promotion .. FAIL
cumulative_union_sparse_sparse .. FAIL
equal .. PASS
explicit_thresh .. PASS
hash .. PASS
hash_any .. PASS
meta_func .. PASS
murmur_bigint .. PASS
murmur_bytea .. PASS
nosparse .. PASS
notequal .. PASS
scalar_oob .. PASS
storedproc .. PASS
transaction .. PASS
typmod .. PASS
typmod_insert .. PASS
union_op .. PASS
ERROR: 11 / 33 tests failed

Testsuite fails with glibc 2.29

Ubuntu's regression testing has found that postgresql-hll's regression testsuite fails with glibc 2.29, and I'm not entirely sure what to make of the output:

=======================
 3 of 34 tests failed. 
=======================
**** regression.diffs ****
--- /home/adconrad/hll/postgresql-hll-2.12/expected/cumulative_add_cardinality_correction.out	2018-11-02 16:44:11.000000000 -0600
+++ /home/adconrad/hll/postgresql-hll-2.12/results/cumulative_add_cardinality_correction.out	2019-03-05 11:31:05.367563496 -0700
@@ -61,7 +61,10 @@
  ORDER BY curr.recno;
  recno |   cardinality    | hll_cardinality  
 -------+------------------+------------------
+   633 | 755.768753982942 | 755.768753982942
+   710 | 870.278431678927 | 870.278431678927
+   941 | 1258.10097940924 | 1258.10097940924
   1792 | 4250.71186178904 | 4250.71186178904
-(1 row)
+(4 rows)
 
 DROP TABLE test_msgfjqhm;

======================================================================

--- /home/adconrad/hll/postgresql-hll-2.12/expected/cumulative_add_comprehensive_promotion.out	2018-11-02 16:44:11.000000000 -0600
+++ /home/adconrad/hll/postgresql-hll-2.12/results/cumulative_add_comprehensive_promotion.out	2019-03-05 11:31:05.998561429 -0700
@@ -61,6 +61,10 @@
  ORDER BY curr.recno;
  recno |   cardinality    | hll_cardinality  
 -------+------------------+------------------
+   744 | 755.768753982942 | 755.768753982942
+   871 | 870.278431678927 | 870.278431678927
+   872 | 870.278431678927 | 870.278431678927
+  1250 | 1258.10097940924 | 1258.10097940924
   4343 | 4250.71186178904 | 4250.71186178904
   4344 | 4250.71186178904 | 4250.71186178904
   4345 | 4250.71186178904 | 4250.71186178904
@@ -76,6 +80,6 @@
   4355 | 4250.71186178904 | 4250.71186178904
   4356 | 4250.71186178904 | 4250.71186178904
   4357 | 4250.71186178904 | 4250.71186178904
-(15 rows)
+(19 rows)
 
 DROP TABLE test_ptwysrqk;

======================================================================

--- /home/adconrad/hll/postgresql-hll-2.12/expected/cumulative_union_sparse_promotion.out	2018-11-02 16:44:11.000000000 -0600
+++ /home/adconrad/hll/postgresql-hll-2.12/results/cumulative_union_sparse_promotion.out	2019-03-05 11:31:22.806506409 -0700
@@ -51,9 +51,13 @@
        hll_cardinality(union_compressed_multiset)
   FROM test_bsnvqefe
  WHERE union_cardinality != hll_cardinality(union_compressed_multiset);
- recno | union_cardinality | hll_cardinality 
--------+-------------------+-----------------
-(0 rows)
+ recno | union_cardinality | hll_cardinality  
+-------+-------------------+------------------
+   772 |  755.768753982942 | 755.768753982942
+   883 |  870.278431678927 | 870.278431678927
+   884 |  870.278431678927 | 870.278431678927
+  1298 |  1258.10097940924 | 1258.10097940924
+(4 rows)
 
 -- Test union of incremental multiset.
 --
@@ -81,9 +85,13 @@
    AND curr.union_cardinality != 
        hll_cardinality(hll_union(curr.compressed_multiset,
                                  prev.union_compressed_multiset));
- recno | union_cardinality | hll_cardinality 
--------+-------------------+-----------------
-(0 rows)
+ recno | union_cardinality | hll_cardinality  
+-------+-------------------+------------------
+   772 |  755.768753982942 | 755.768753982942
+   883 |  870.278431678927 | 870.278431678927
+   884 |  870.278431678927 | 870.278431678927
+  1298 |  1258.10097940924 | 1258.10097940924
+(4 rows)
 
 -- Test aggregate accumulation
 --

======================================================================

To my untrained eye, the left and right sides look the same to me, so I'm not entirely sure what's up here, but I also have zero knowledge or experience with HLL.

Using hll_cardinality(hll_union_agg(users)) with OVER partition by

Hi,
There is an example about using #hll_union_agg(users) OVER (ORDER BY date ASC ROWS 6 PRECEDING).

However if I try to use it with OVER(partition by date) it does not work: ERROR: column "users" must appear in the GROUP BY clause or be used in an aggregate function.

Build problems on Mac OSX Mojave

My builds failed with

clang -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -O2  -std=c99 -fPIC -Wall -Wextra -Werror -Wno-unused-parameter -Wno-implicit-fallthrough -Iinclude -I/usr/local/Cellar/postgresql/11.2/include -I. -I./ -I/usr/local/Cellar/postgresql/11.2/include/server -I/usr/local/Cellar/postgresql/11.2/include/internal -I/usr/local/Cellar/icu4c/63.1/include -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/libxml2   -c -o src/hll.o src/hll.c
clang: error: no such sysroot directory: '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk' [-Werror,-Wmissing-sysroot]
make: *** [src/hll.o] Error 1

And after removing -Werror in the makefile

λ make
clang -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -O2  -std=c99 -fPIC -Wall -Wextra -Wno-unused-parameter -Wno-implicit-fallthrough -Iinclude -I/usr/local/Cellar/postgresql/11.2/include -I. -I./ -I/usr/local/Cellar/postgresql/11.2/include/server -I/usr/local/Cellar/postgresql/11.2/include/internal -I/usr/local/Cellar/icu4c/63.1/include -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/libxml2   -c -o src/hll.o src/hll.c
clang: warning: no such sysroot directory: '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk' [-Wmissing-sysroot]
In file included from src/hll.c:16:
In file included from /usr/local/Cellar/postgresql/11.2/include/server/postgres.h:46:
/usr/local/Cellar/postgresql/11.2/include/server/c.h:59:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^~~~~~~~~
1 error generated.
make: *** [src/hll.o] Error 1

After installing header files via open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg (From neovim/neovim#9050 (comment)) and adding -I/usr/include to the cpp flags, it compiled.

I ended up with this PG_CPPFLAGS:

PG_CPPFLAGS = -fPIC -Wall -Wextra -Wno-unused-parameter -Wno-implicit-fallthrough -Iinclude -I$(libpq_srcdir) -I/usr/include

Setting regwidth >= 6 results in cardinality computed to NaN

Setting it to 5 works just fine, but setting it to 6 (Regardless log2m selected) always results in NaN.

Pulled the code locally to test the implementation against our implementation of HLL, and I noticed that issue. It's really hll.c with PG callback/integration bits removed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.