云原生数据仓库AnalyticDB PostgreSQL版除原生Greenplum Database功能外,还支持HyperLogLog,能够为互联网广告分析及有类似预估分析计算需求的行业提供解决方案,以便于快速预估PV、UV等业务指标。

重要 V6.3.8.9及以后版本,安装或升级插件需要提交工单联系技术支持进行处理。

如何查看实例内核版本,请参见查看内核小版本

创建HyperLogLog插件

执行如下命令,创建HyperLogLog插件:

CREATE EXTENSION hll;

基本类型

  • 执行如下命令,创建一个含有hll字段的表:

    create table agg (id int primary key,userids hll);
  • 执行如下命令,进行int转hll_hashval:

    select 1::hll_hashval;

基本操作符

  • hll类型支持=、!=、<>、|| 和 #。
    select hll_add_agg(1::hll_hashval) = hll_add_agg(2::hll_hashval);
    select hll_add_agg(1::hll_hashval) || hll_add_agg(2::hll_hashval);
    select #hll_add_agg(1::hll_hashval);
  • hll_hashval类型支持=、!= 和 <>。
    select 1::hll_hashval = 2::hll_hashval;
    select 1::hll_hashval <> 2::hll_hashval;

基本函数

  • hll_hash_boolean、hll_hash_smallint和hll_hash_bigint等hash函数。
    select hll_hash_boolean(true);
    select hll_hash_integer(1);
  • hll_add_agg:可以将int转hll格式。
    select hll_add_agg(1::hll_hashval);
  • hll_union:hll并集。
    select hll_union(hll_add_agg(1::hll_hashval),hll_add_agg(2::hll_hashval));
  • hll_set_defaults:设置精度。
    select hll_set_defaults(15,5,-1,1);
  • hll_print:用于debug信息。
    select hll_print(hll_add_agg(1::hll_hashval));

示例

create table access_date (acc_date date unique, userids hll);
insert into access_date select current_date, hll_add_agg(hll_hash_integer(user_id)) from generate_series(1,10000) t(user_id);
insert into access_date select current_date-1, hll_add_agg(hll_hash_integer(user_id)) from generate_series(5000,20000) t(user_id);
insert into access_date select current_date-2, hll_add_agg(hll_hash_integer(user_id)) from generate_series(9000,40000) t(user_id);
postgres=# select #userids from access_date where acc_date=current_date;
     ?column?
------------------
 9725.85273370708
(1 row)
postgres=# select #userids from access_date where acc_date=current_date-1;
     ?column?
------------------
 14968.6596883279
(1 row)
postgres=# select #userids from access_date where acc_date=current_date-2;
     ?column?
------------------
 29361.5209149911
(1 row)