faiss-napi provides Node/Bun/Deno NAPI bindings for faiss
This package is a fork of the original faiss-node with a focus on advanced features & performance.
$ npm install faiss-napiconst{ IndexFlatL2, Index, IndexFlatIP, IndexHNSW, MetricType }=require('faiss-napi');constdimension=2;constindex=newIndexFlatL2(dimension);console.log(index.dims);// 2console.log(index.isTrained);// trueconsole.log(index.ntotal);// 0// inserting data into index.index.add([1,0]);index.add([1,2]);index.add([1,3]);index.add([1,1]);console.log(index.ntotal);// 4constk=4;constresults=index.search([1,0],k);console.log(results.labels);// [ 0n, 3n, 1n, 2n ]console.log(results.distances);// [ 0, 1, 4, 9 ]// Save indexconstfname='faiss.index';index.write(fname);// Load saved indexconstindex_loaded=IndexFlatL2.read(fname);console.log(index_loaded.dims);//2console.log(index_loaded.ntotal);//4constresults1=index_loaded.search([1,1],4);console.log(results1.labels);// [ 3n, 0n, 1n, 2n ]console.log(results1.distances);// [ 0, 1, 1, 4 ]// Merge indexconstnewIndex=newIndexFlatL2(dimension);newIndex.mergeFrom(index);console.log(newIndex.ntotal);// 4// Remove itemsconsole.log(newIndex.search([1,2],1));// { distances: [ 0 ], labels: [ 1n ] }constremovedCount=newIndex.removeIds([0]);console.log(removedCount);// 1console.log(newIndex.ntotal);// 3console.log(newIndex.search([1,2],1));// { distances: [ 0 ], labels: [ 0n ] }// IndexFlatIPconstipIndex=newIndexFlatIP(2);ipIndex.add([1,0]);// Serialize an indexconstindex_buf=newIndex.toBuffer();constdeserializedIndex=Index.fromBuffer(index_buf);console.log(deserializedIndex.ntotal);// 3// Factory indexconsthnswIndex=Index.fromFactory(2,'HNSW32,Flat',MetricType.METRIC_INNER_PRODUCT);// same as:// const hnswIndex = new IndexHNSW(2, 32, MetricType.METRIC_INNER_PRODUCT)constx=[1,0,0,1];hnswIndex.train(x);hnswIndex.add(x);// IDMap'd indexconstidIndex=newIndexFlatL2(2).toIDMap2();constvectors=[[1,0],[0,1]];idIndex.addWithIds(vectors.flat(),[100n,200n]);// reconstruct vectorsexpect(idIndex.reconstruct(idIndex.ids[0])).toEqual(vectors[0]);expect(idIndex.reconstructBatch(idIndex.ids)).toEqual(vectors.flat());// IVFconstivf=newIndexIVFFlat(newIndexFlatL2(2),2,2);constx=Array.from({length: 400},()=>Math.random());consty=Array.from({length: 200},(_,i)=>i);consttrained=newIndexIVFFlat(newIndexFlatL2(2),2,2);trained.train(x.slice(0,200));trained.addWithIds(x.slice(0,200),y.slice(0,100));trained.write('trained.ivf');constuntrained=newIndexIVFFlat(newIndexFlatL2(2),2,2);untrained.addWithIds(x.slice(200),y.slice(100));untrained.write('untrained.ivf');IndexIVFFlat.mergeOnDisk(['trained.ivf','untrained.ivf'],'merged.ivf','merged.ivfdata');MIT