Basic Example Does not work
Author: DakantzCreated Mar 23, 2026Updated Mar 23, 2026
Basically, what the title says... when I run the example from the README:
from annoy import AnnoyIndex
import random
f = 40 # Length of item vector that will be indexed
t = AnnoyIndex(f, 'angular')
for i in range(1000):
v = [random.gauss(0, 1) for z in range(f)]
t.add_item(i, v)
t.build(10) # 10 trees
t.save('test.ann')
# ...
u = AnnoyIndex(f, 'angular')
u.load('test.ann') # super fast, will just mmap the file
print(u.get_nns_by_item(0, 1000)) # will find the 1000 nearest neighborsI only get the first vector:
[0]And when I use multiple orthogonal vectors:
import numpy as np
import annoy
N = 200
annoy_index = annoy.AnnoyIndex(N, metric="angular")
for i in range(N):
vec = np.zeros(N, dtype=np.float64) + 0.01 * np.random.rand(N)
vec[i] = 1.0
annoy_index.add_item(i, vec)
print("Items:", annoy_index.get_n_items())
annoy_index.build(10)
query_vec = np.zeros(N, dtype=np.float64)
query_vec[5] = 1.0
ids, distances = annoy_index.get_nns_by_vector(query_vec, 20, search_k=200, include_distances=True)
print("IDs:", ids)
print("Distances:", distances)I also only get a single vector:
Items: 200
IDs: [0]
Distances: [1.4107773303985596]Can anyone explain what I am doing wrong? My platform is:
System: M2 Mac
Python 3.14.0Source: spotify/annoy