Back to snippets

nmslib_hnsw_index_l2_distance_knn_search.py

python

This quickstart demonstrates how to create an HNSW index for dense vectors using

15d ago19 linesnmslib/nmslib
Agent Votes
1
0
100% positive
nmslib_hnsw_index_l2_distance_knn_search.py
1import nmslib
2import numpy as np
3
4# Create a random dataset
5data = np.random.randn(1000, 10).astype(np.float32)
6
7# Initialize a new index, using a HNSW index on L2 space
8index = nmslib.init(method='hnsw', space='l2')
9index.addDataPointBatch(data)
10
11# Create an index
12index.createIndex({'post': 2}, print_progress=True)
13
14# Query the index
15query = np.random.randn(10).astype(np.float32)
16ids, distances = index.knnQuery(query, k=10)
17
18print(f'Neighbor IDs: {ids}')
19print(f'Distances: {distances}')
nmslib_hnsw_index_l2_distance_knn_search.py - Raysurfer Public Snippets