nn-rs is a pure Rust library for finding the nearest neighbours for 1-D vectors using nalgebra.
You can create an empty NearestNeighbour Index and add vectors to it ```rust use nn_rs::NearestNeighbours; use nalgebra;
// pick a metric to use let metric = String::from("cosine"); // create an empty index let mut index: NearestNeighbours = NearestNeighbours::new(metric)?;
// create some dummy vectors
let a: nalgebra::DVector
// add these dummy vectors to the index index.addvector(String::from("a"), a)?; index.addvector(String::from("b"), b)?; index.addvector(String::from("c"), c)?; index.addvector(String::from("d"), d)?; ```
You can then save this to a .nn file which be can re-loaded
```rust
use std::path::PathBuf;
let savepath = PathBuf::from("./test.nn"); index.save(savepath)?;
let loadpath = PathBuf::from("./test.nn"); let mut newindex = NearestNeighbours.load(load_path)?; ```
Alternatively, you can create the index from a json
json
{
"a": [1.0, 2.0, 3.0],
"b": [7.0, 2.0, 9.0],
"c": [4.0, 2.1, 3.4],
"d": [0.9, 8.2, 4.6]
}
rust
let json_path = PathBuf::from("some.json");
let metric = String::from("cosine");
let mut index = NearestNeighbours::from_json(metric, json_path)?;
Once you have an index you can then query by vector to find the nearest n vectors
rust
let query_vector: nalgebra::DVector<f64> = nalgebra::dvector!(1.0, 2.0, 3.0);
// the number of neighbours to return
let n: uszie = 1;
// find just the single nearest neighbour in the index
let nearest_neighbour = index.query_by_vector(query_vector, n)?;
Add the following line to your Cargo.toml file:
toml
[dependencies]
nn-rs = "0.1.2"