全部產品
Search
文件中心

AnalyticDB for PostgreSQL:使用HyperLogLog

更新時間:Feb 05, 2024

雲原生資料倉儲AnalyticDB PostgreSQL版除原生Greenplum Database功能外,還支援HyperLogLog,能夠為互連網廣告分析及有類似預估分析計算需求的行業提供解決方案,以便於快速預估PV、UV等業務指標。

重要

建立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)