From: spyderdfx (@spyderdfx) <noreply+spyderdfx@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #972: Binary vectors - querying the nearest neighbors by Hamming distance with HNSW gives wrong results
Date: Sun, 29 Mar 2026 10:04:01 +0000
Message-ID: <gh-pgvector-pgvector-972@github.com> (raw)
Hi. So, I have pgvector 0.8.1, postgres 17.7, and a table like this with ~20kk records:
```ruby
create_table :image_hashes do |t|
t.column :external_id, :integer, null: false
t.column :vector_binary, :bit, limit: 576
t.timestamps
end
add_index :image_hashes, :external_id, unique: true
execute 'CREATE INDEX ON image_hashes USING hnsw (vector_binary bit_hamming_ops);'
```
I clearly see that the needed record is in the table:
```
SELECT (vector_binary <~> '<576 bits omitted>') AS distance FROM image_hashes WHERE external_id = 608810322 LIMIT 1;
distance
----------
0
(1 row)
```
But querying the nearest neighbors gives unexpected results:
```
SELECT (vector_binary <~> '<here are 576 bits>') AS distance FROM image_hashes ORDER BY (vector_binary <~> '<576 bits omitted>') LIMIT 5;
distance
----------
257
257
257
257
257
(5 rows)
```
Here's query plan:
```
Limit (cost=96.28..110.07 rows=5 width=8) (actual time=1.190..1.195 rows=5 loops=1)
-> Index Scan using image_hashes_vector_binary_idx on image_hashes (cost=96.28..55469151.36 rows=20117568 width=8) (actual time=1.185..1.189 rows=5 loops=1)
Order By: (vector_binary <~> '<576 bits omitted>'::"bit")
Planning Time: 1.797 ms
Execution Time: 1.319 ms
(5 rows)
```
At first I thought that maybe something wrong with the index. I recreated it but nothing changed.
So, what am I doing wrong?