全部產品
Search
文件中心

ApsaraDB RDS:基數統計(hll)

更新時間:Jun 19, 2024

hll外掛程式支援的資料類型HyperLogLog可以協助您快速預估PV、UV等業務指標。

前提條件

  • 請確保執行個體大版本滿足要求,本外掛程式具體支援的執行個體大版本,請參見支援外掛程式列表

  • 如執行個體大版本已滿足要求,但仍提示不支援,請升級核心小版本,具體操作,請參見升級核心小版本

背景資訊

hll外掛程式支援一種可變長、類似集合的資料類型HyperLogLog(hll),常用於在指定精度下返回近似的distinct值,例如1280位元組的hll資料類型可以高精度地估計出近百億的distinct值。hll適合互連網廣告分析或其他有類似預估分析計算需求的行業,可以快速預估PV、UV等業務指標。

更多hll外掛程式使用方法請參見postgresql-hll

詳細演算法說明請參見論文HyperLogLog: the analysis of a near-optimalcardinality estimation algorithm

建立hll外掛程式

串連執行個體後建立hll外掛程式,命令如下:

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)RDS PostgreSQL 11或以上版本均支援此功能,如提示不支援,請升級核心小版本,具體操作,請參見升級核心小版本。