Elffuss BraidHub

kikocis/lancedb public

bbc8a2ecbe2c · 3.0 KiBRawPermalink
1// Copyright 2024 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Mutex;
16
17use lancedb::index::scalar::{BTreeIndexBuilder, FtsIndexBuilder};
18use lancedb::index::vector::IvfPqIndexBuilder;
19use lancedb::index::Index as LanceDbIndex;
20use napi_derive::napi;
21
22use crate::util::parse_distance_type;
23
24#[napi]
25pub struct Index {
26 inner: Mutex<Option<LanceDbIndex>>,
27}
28
29impl Index {
30 pub fn consume(&self) -> napi::Result<LanceDbIndex> {
31 self.inner
32 .lock()
33 .unwrap()
34 .take()
35 .ok_or(napi::Error::from_reason(
36 "attempt to use an index more than once",
37 ))
38 }
39}
40
41#[napi]
42impl Index {
43 #[napi(factory)]
44 pub fn ivf_pq(
45 distance_type: Option<String>,
46 num_partitions: Option<u32>,
47 num_sub_vectors: Option<u32>,
48 max_iterations: Option<u32>,
49 sample_rate: Option<u32>,
50 ) -> napi::Result<Self> {
51 let mut ivf_pq_builder = IvfPqIndexBuilder::default();
52 if let Some(distance_type) = distance_type {
53 let distance_type = parse_distance_type(distance_type)?;
54 ivf_pq_builder = ivf_pq_builder.distance_type(distance_type);
55 }
56 if let Some(num_partitions) = num_partitions {
57 ivf_pq_builder = ivf_pq_builder.num_partitions(num_partitions);
58 }
59 if let Some(num_sub_vectors) = num_sub_vectors {
60 ivf_pq_builder = ivf_pq_builder.num_sub_vectors(num_sub_vectors);
61 }
62 if let Some(max_iterations) = max_iterations {
63 ivf_pq_builder = ivf_pq_builder.max_iterations(max_iterations);
64 }
65 if let Some(sample_rate) = sample_rate {
66 ivf_pq_builder = ivf_pq_builder.sample_rate(sample_rate);
67 }
68 Ok(Self {
69 inner: Mutex::new(Some(LanceDbIndex::IvfPq(ivf_pq_builder))),
70 })
71 }
72
73 #[napi(factory)]
74 pub fn btree() -> Self {
75 Self {
76 inner: Mutex::new(Some(LanceDbIndex::BTree(BTreeIndexBuilder::default()))),
77 }
78 }
79
80 #[napi(factory)]
81 pub fn bitmap() -> Self {
82 Self {
83 inner: Mutex::new(Some(LanceDbIndex::Bitmap(Default::default()))),
84 }
85 }
86
87 #[napi(factory)]
88 pub fn label_list() -> Self {
89 Self {
90 inner: Mutex::new(Some(LanceDbIndex::LabelList(Default::default()))),
91 }
92 }
93
94 #[napi(factory)]
95 pub fn fts() -> Self {
96 Self {
97 inner: Mutex::new(Some(LanceDbIndex::FTS(FtsIndexBuilder::default()))),
98 }
99 }
100}