-- 创建表 createtable if notexists int8tmp_2 ( a bigint );
-- 写入一百万条数据 INSERTINTO int8tmp_2 SELECT val FROM (SELECTsqrt(random()) :: NUMERIC*9223372036854775807*2- 9223372036854775807 :: NUMERICAS val FROM generate_series(1, 1000000)) t; -- 创建一个查询函数 CREATEOR REPLACE FUNCTION bit_count(valueBIGINT) RETURNSNUMERIC AS $$ SELECTSUM((value>> bit) &1) FROM generate_series(0, 63) bit $$ LANGUAGESQL IMMUTABLE STRICT;
-- 查询 SELECT a, bit_count(a # 8192711222023195111) AS hd FROM int8tmp_2 WHERE bit_count(a # 8192711222023195111) <4 ORDERBY hd;
-- 结果大概这样 -- [2018-03-04 11:06:56] 1 row retrieved starting from 1 in 25s 403ms (execution: 25s 383ms, fetching: 20ms)
-- 启用扩展 CREATE EXTENSION bktree; -- 创建 CREATE INDEX IF NOTEXISTS int8idx_2 ON int8tmp_2 USING spgist ( a bktree_ops ); -- 查询( <-> 运算符表示计算汉明距离, <@()表示符合汉明距离小于N) SELECT a, a <->8192711222023195111AS hd FROM int8tmp_2 WHERE a <@ (8192711222023195111, 4) ORDERBY hd; -- 结果大概是这样的 [2018-03-0411:18:25] 1row retrieved starting from1in44ms (execution: 31ms, fetching: 13ms)