bktree
bktree · SP-GiST BK-tree index extension for 64-bit perceptual hashes and Hamming-distance searches.
Overview
PostgreSQL · 15
Usage
Sources:
bktree provides a BK-tree operator class for SP-GiST indexes over 64-bit integer hashes. Its distance is the Hamming distance between the two bit patterns, making it useful for nearest-neighbor-like filtering of perceptual hashes rather than ordinary numeric ranges.
Core Workflow
Store each 64-bit hash as bigint, build the bktree_ops index, and query with a bktree_area containing the center and maximum distance.
The <@ operator tests whether the Hamming distance is at most the requested radius. The <-> operator returns the distance, while the extension’s = operator tests bitwise equality. int64_to_bitstring() and bitstring_to_int64() are conversion helpers.
Caveats
The operator class is only for int8 and the implementation assumes a 64-bit Hamming distance from 0 through 64. A radius is not a numeric tolerance: nearby integer values may have many differing bits, and distant integer values may have few. The reviewed fork specifically targets PostgreSQL 15; validate index creation, plans, equality semantics, and signed hash conversion on the exact server build before production use.