@lancedb/lancedb 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/arrow.d.ts +2 -3
  2. package/dist/arrow.js +2 -27
  3. package/dist/connection.d.ts +9 -0
  4. package/dist/connection.js +16 -2
  5. package/dist/embedding/embedding_function.d.ts +11 -0
  6. package/dist/embedding/embedding_function.js +28 -7
  7. package/dist/embedding/index.d.ts +2 -1
  8. package/dist/embedding/index.js +7 -6
  9. package/dist/embedding/openai.d.ts +1 -1
  10. package/dist/embedding/registry.d.ts +9 -7
  11. package/dist/embedding/registry.js +24 -6
  12. package/dist/embedding/transformers.d.ts +37 -0
  13. package/dist/embedding/transformers.js +147 -0
  14. package/dist/index.d.ts +1 -1
  15. package/dist/query.js +15 -9
  16. package/dist/remote/client.d.ts +1 -1
  17. package/dist/remote/client.js +6 -8
  18. package/dist/remote/connection.d.ts +2 -3
  19. package/dist/remote/connection.js +2 -2
  20. package/dist/sanitize.js +4 -2
  21. package/dist/table.d.ts +3 -0
  22. package/dist/table.js +1 -1
  23. package/package.json +17 -13
  24. package/Cargo.toml +0 -28
  25. package/biome.json +0 -158
  26. package/build.rs +0 -5
  27. package/dist/native.d.ts +0 -208
  28. package/examples/ann_indexes.ts +0 -49
  29. package/examples/basic.ts +0 -149
  30. package/examples/embedding.ts +0 -83
  31. package/examples/filtering.ts +0 -34
  32. package/examples/jsconfig.json +0 -27
  33. package/examples/package-lock.json +0 -79
  34. package/examples/package.json +0 -18
  35. package/examples/search.ts +0 -37
  36. package/jest.config.js +0 -7
  37. package/lancedb/arrow.ts +0 -947
  38. package/lancedb/connection.ts +0 -333
  39. package/lancedb/embedding/embedding_function.ts +0 -194
  40. package/lancedb/embedding/index.ts +0 -113
  41. package/lancedb/embedding/openai.ts +0 -113
  42. package/lancedb/embedding/registry.ts +0 -188
  43. package/lancedb/index.ts +0 -142
  44. package/lancedb/indices.ts +0 -203
  45. package/lancedb/merge.ts +0 -70
  46. package/lancedb/query.ts +0 -507
  47. package/lancedb/remote/client.ts +0 -221
  48. package/lancedb/remote/connection.ts +0 -201
  49. package/lancedb/remote/index.ts +0 -3
  50. package/lancedb/remote/table.ts +0 -226
  51. package/lancedb/sanitize.ts +0 -588
  52. package/lancedb/table.ts +0 -669
  53. package/lancedb/util.ts +0 -69
  54. package/native.d.ts +0 -208
  55. package/nodejs-artifacts/arrow.d.ts +0 -250
  56. package/nodejs-artifacts/arrow.js +0 -768
  57. package/nodejs-artifacts/connection.d.ts +0 -171
  58. package/nodejs-artifacts/connection.js +0 -135
  59. package/nodejs-artifacts/embedding/embedding_function.d.ts +0 -79
  60. package/nodejs-artifacts/embedding/embedding_function.js +0 -112
  61. package/nodejs-artifacts/embedding/index.d.ts +0 -28
  62. package/nodejs-artifacts/embedding/index.js +0 -114
  63. package/nodejs-artifacts/embedding/openai.d.ts +0 -18
  64. package/nodejs-artifacts/embedding/openai.js +0 -105
  65. package/nodejs-artifacts/embedding/registry.d.ts +0 -53
  66. package/nodejs-artifacts/embedding/registry.js +0 -127
  67. package/nodejs-artifacts/index.d.ts +0 -55
  68. package/nodejs-artifacts/index.js +0 -57
  69. package/nodejs-artifacts/indices.d.ts +0 -165
  70. package/nodejs-artifacts/indices.js +0 -71
  71. package/nodejs-artifacts/merge.d.ts +0 -54
  72. package/nodejs-artifacts/merge.js +0 -64
  73. package/nodejs-artifacts/native.d.ts +0 -208
  74. package/nodejs-artifacts/native.js +0 -330
  75. package/nodejs-artifacts/query.d.ts +0 -283
  76. package/nodejs-artifacts/query.js +0 -448
  77. package/nodejs-artifacts/remote/client.d.ts +0 -28
  78. package/nodejs-artifacts/remote/client.js +0 -172
  79. package/nodejs-artifacts/remote/connection.d.ts +0 -25
  80. package/nodejs-artifacts/remote/connection.js +0 -110
  81. package/nodejs-artifacts/remote/index.d.ts +0 -3
  82. package/nodejs-artifacts/remote/index.js +0 -9
  83. package/nodejs-artifacts/remote/table.d.ts +0 -42
  84. package/nodejs-artifacts/remote/table.js +0 -179
  85. package/nodejs-artifacts/sanitize.d.ts +0 -31
  86. package/nodejs-artifacts/sanitize.js +0 -436
  87. package/nodejs-artifacts/table.d.ts +0 -395
  88. package/nodejs-artifacts/table.js +0 -230
  89. package/nodejs-artifacts/util.d.ts +0 -14
  90. package/nodejs-artifacts/util.js +0 -65
  91. package/tsconfig.json +0 -25
  92. package/typedoc.json +0 -10
@@ -1,113 +0,0 @@
1
- // Copyright 2023 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
-
15
- import type OpenAI from "openai";
16
- import { type EmbeddingCreateParams } from "openai/resources";
17
- import { Float, Float32 } from "../arrow";
18
- import { EmbeddingFunction } from "./embedding_function";
19
- import { register } from "./registry";
20
-
21
- export type OpenAIOptions = {
22
- apiKey: string;
23
- model: EmbeddingCreateParams["model"];
24
- };
25
-
26
- @register("openai")
27
- export class OpenAIEmbeddingFunction extends EmbeddingFunction<
28
- string,
29
- Partial<OpenAIOptions>
30
- > {
31
- #openai: OpenAI;
32
- #modelName: OpenAIOptions["model"];
33
-
34
- constructor(
35
- options: Partial<OpenAIOptions> = {
36
- model: "text-embedding-ada-002",
37
- },
38
- ) {
39
- super();
40
- const openAIKey = options?.apiKey ?? process.env.OPENAI_API_KEY;
41
- if (!openAIKey) {
42
- throw new Error("OpenAI API key is required");
43
- }
44
- const modelName = options?.model ?? "text-embedding-ada-002";
45
-
46
- /**
47
- * @type {import("openai").default}
48
- */
49
- // eslint-disable-next-line @typescript-eslint/naming-convention
50
- let Openai;
51
- try {
52
- // eslint-disable-next-line @typescript-eslint/no-var-requires
53
- Openai = require("openai");
54
- } catch {
55
- throw new Error("please install openai@^4.24.1 using npm install openai");
56
- }
57
-
58
- const configuration = {
59
- apiKey: openAIKey,
60
- };
61
-
62
- this.#openai = new Openai(configuration);
63
- this.#modelName = modelName;
64
- }
65
-
66
- toJSON() {
67
- return {
68
- model: this.#modelName,
69
- };
70
- }
71
-
72
- ndims(): number {
73
- switch (this.#modelName) {
74
- case "text-embedding-ada-002":
75
- return 1536;
76
- case "text-embedding-3-large":
77
- return 3072;
78
- case "text-embedding-3-small":
79
- return 1536;
80
- default:
81
- throw new Error(`Unknown model: ${this.#modelName}`);
82
- }
83
- }
84
-
85
- embeddingDataType(): Float {
86
- return new Float32();
87
- }
88
-
89
- async computeSourceEmbeddings(data: string[]): Promise<number[][]> {
90
- const response = await this.#openai.embeddings.create({
91
- model: this.#modelName,
92
- input: data,
93
- });
94
-
95
- const embeddings: number[][] = [];
96
- for (let i = 0; i < response.data.length; i++) {
97
- embeddings.push(response.data[i].embedding);
98
- }
99
- return embeddings;
100
- }
101
-
102
- async computeQueryEmbeddings(data: string): Promise<number[]> {
103
- if (typeof data !== "string") {
104
- throw new Error("Data must be a string");
105
- }
106
- const response = await this.#openai.embeddings.create({
107
- model: this.#modelName,
108
- input: data,
109
- });
110
-
111
- return response.data[0].embedding;
112
- }
113
- }
@@ -1,188 +0,0 @@
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
-
15
- import {
16
- type EmbeddingFunction,
17
- type EmbeddingFunctionConstructor,
18
- } from "./embedding_function";
19
- import "reflect-metadata";
20
- import { OpenAIEmbeddingFunction } from "./openai";
21
-
22
- interface EmbeddingFunctionCreate<T extends EmbeddingFunction> {
23
- create(options?: T["TOptions"]): T;
24
- }
25
-
26
- /**
27
- * This is a singleton class used to register embedding functions
28
- * and fetch them by name. It also handles serializing and deserializing.
29
- * You can implement your own embedding function by subclassing EmbeddingFunction
30
- * or TextEmbeddingFunction and registering it with the registry
31
- */
32
- export class EmbeddingFunctionRegistry {
33
- #functions = new Map<string, EmbeddingFunctionConstructor>();
34
-
35
- /**
36
- * Register an embedding function
37
- * @param name The name of the function
38
- * @param func The function to register
39
- * @throws Error if the function is already registered
40
- */
41
- register<
42
- T extends EmbeddingFunctionConstructor = EmbeddingFunctionConstructor,
43
- >(
44
- this: EmbeddingFunctionRegistry,
45
- alias?: string,
46
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
47
- ): (ctor: T) => any {
48
- const self = this;
49
- return function (ctor: T) {
50
- if (!alias) {
51
- alias = ctor.name;
52
- }
53
- if (self.#functions.has(alias)) {
54
- throw new Error(
55
- `Embedding function with alias "${alias}" already exists`,
56
- );
57
- }
58
- self.#functions.set(alias, ctor);
59
- Reflect.defineMetadata("lancedb::embedding::name", alias, ctor);
60
- return ctor;
61
- };
62
- }
63
-
64
- /**
65
- * Fetch an embedding function by name
66
- * @param name The name of the function
67
- */
68
- get<T extends EmbeddingFunction<unknown>, Name extends string = "">(
69
- name: Name extends "openai" ? "openai" : string,
70
- //This makes it so that you can use string constants as "types", or use an explicitly supplied type
71
- // ex:
72
- // `registry.get("openai") -> EmbeddingFunctionCreate<OpenAIEmbeddingFunction>`
73
- // `registry.get<MyCustomEmbeddingFunction>("my_func") -> EmbeddingFunctionCreate<MyCustomEmbeddingFunction> | undefined`
74
- //
75
- // the reason this is important is that we always know our built in functions are defined so the user isnt forced to do a non null/undefined
76
- // ```ts
77
- // const openai: OpenAIEmbeddingFunction = registry.get("openai").create()
78
- // ```
79
- ): Name extends "openai"
80
- ? EmbeddingFunctionCreate<OpenAIEmbeddingFunction>
81
- : EmbeddingFunctionCreate<T> | undefined {
82
- type Output = Name extends "openai"
83
- ? EmbeddingFunctionCreate<OpenAIEmbeddingFunction>
84
- : EmbeddingFunctionCreate<T> | undefined;
85
-
86
- const factory = this.#functions.get(name);
87
- if (!factory) {
88
- return undefined as Output;
89
- }
90
-
91
- return {
92
- create: function (options?: T["TOptions"]) {
93
- return new factory(options);
94
- },
95
- } as Output;
96
- }
97
-
98
- /**
99
- * reset the registry to the initial state
100
- */
101
- reset(this: EmbeddingFunctionRegistry) {
102
- this.#functions.clear();
103
- }
104
-
105
- /**
106
- * @ignore
107
- */
108
- parseFunctions(
109
- this: EmbeddingFunctionRegistry,
110
- metadata: Map<string, string>,
111
- ): Map<string, EmbeddingFunctionConfig> {
112
- if (!metadata.has("embedding_functions")) {
113
- return new Map();
114
- } else {
115
- type FunctionConfig = {
116
- name: string;
117
- sourceColumn: string;
118
- vectorColumn: string;
119
- model: EmbeddingFunction["TOptions"];
120
- };
121
- const functions = <FunctionConfig[]>(
122
- JSON.parse(metadata.get("embedding_functions")!)
123
- );
124
- return new Map(
125
- functions.map((f) => {
126
- const fn = this.get(f.name);
127
- if (!fn) {
128
- throw new Error(`Function "${f.name}" not found in registry`);
129
- }
130
- return [
131
- f.name,
132
- {
133
- sourceColumn: f.sourceColumn,
134
- vectorColumn: f.vectorColumn,
135
- function: this.get(f.name)!.create(f.model),
136
- },
137
- ];
138
- }),
139
- );
140
- }
141
- }
142
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
143
- functionToMetadata(conf: EmbeddingFunctionConfig): Record<string, any> {
144
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
145
- const metadata: Record<string, any> = {};
146
- const name = Reflect.getMetadata(
147
- "lancedb::embedding::name",
148
- conf.function.constructor,
149
- );
150
- metadata["sourceColumn"] = conf.sourceColumn;
151
- metadata["vectorColumn"] = conf.vectorColumn ?? "vector";
152
- metadata["name"] = name ?? conf.function.constructor.name;
153
- metadata["model"] = conf.function.toJSON();
154
- return metadata;
155
- }
156
-
157
- getTableMetadata(functions: EmbeddingFunctionConfig[]): Map<string, string> {
158
- const metadata = new Map<string, string>();
159
- const jsonData = functions.map((conf) => this.functionToMetadata(conf));
160
- metadata.set("embedding_functions", JSON.stringify(jsonData));
161
-
162
- return metadata;
163
- }
164
- }
165
-
166
- const _REGISTRY = new EmbeddingFunctionRegistry();
167
-
168
- export function register(name?: string) {
169
- return _REGISTRY.register(name);
170
- }
171
-
172
- /**
173
- * Utility function to get the global instance of the registry
174
- * @returns `EmbeddingFunctionRegistry` The global instance of the registry
175
- * @example
176
- * ```ts
177
- * const registry = getRegistry();
178
- * const openai = registry.get("openai").create();
179
- */
180
- export function getRegistry(): EmbeddingFunctionRegistry {
181
- return _REGISTRY;
182
- }
183
-
184
- export interface EmbeddingFunctionConfig {
185
- sourceColumn: string;
186
- vectorColumn?: string;
187
- function: EmbeddingFunction;
188
- }
package/lancedb/index.ts DELETED
@@ -1,142 +0,0 @@
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
-
15
- import {
16
- Connection,
17
- LocalConnection,
18
- cleanseStorageOptions,
19
- } from "./connection";
20
-
21
- import {
22
- ConnectionOptions,
23
- Connection as LanceDbConnection,
24
- } from "./native.js";
25
-
26
- import { RemoteConnection, RemoteConnectionOptions } from "./remote";
27
-
28
- export {
29
- WriteOptions,
30
- WriteMode,
31
- AddColumnsSql,
32
- ColumnAlteration,
33
- ConnectionOptions,
34
- IndexStatistics,
35
- IndexMetadata,
36
- IndexConfig,
37
- } from "./native.js";
38
-
39
- export {
40
- makeArrowTable,
41
- MakeArrowTableOptions,
42
- Data,
43
- VectorColumnOptions,
44
- } from "./arrow";
45
-
46
- export {
47
- Connection,
48
- CreateTableOptions,
49
- TableNamesOptions,
50
- } from "./connection";
51
-
52
- export {
53
- ExecutableQuery,
54
- Query,
55
- QueryBase,
56
- VectorQuery,
57
- RecordBatchIterator,
58
- } from "./query";
59
-
60
- export { Index, IndexOptions, IvfPqOptions } from "./indices";
61
-
62
- export { Table, AddDataOptions, UpdateOptions } from "./table";
63
-
64
- export * as embedding from "./embedding";
65
-
66
- /**
67
- * Connect to a LanceDB instance at the given URI.
68
- *
69
- * Accepted formats:
70
- *
71
- * - `/path/to/database` - local database
72
- * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
73
- * - `db://host:port` - remote database (LanceDB cloud)
74
- * @param {string} uri - The uri of the database. If the database uri starts
75
- * with `db://` then it connects to a remote database.
76
- * @see {@link ConnectionOptions} for more details on the URI format.
77
- * @example
78
- * ```ts
79
- * const conn = await connect("/path/to/database");
80
- * ```
81
- * @example
82
- * ```ts
83
- * const conn = await connect(
84
- * "s3://bucket/path/to/database",
85
- * {storageOptions: {timeout: "60s"}
86
- * });
87
- * ```
88
- */
89
- export async function connect(
90
- uri: string,
91
- opts?: Partial<ConnectionOptions | RemoteConnectionOptions>,
92
- ): Promise<Connection>;
93
- /**
94
- * Connect to a LanceDB instance at the given URI.
95
- *
96
- * Accepted formats:
97
- *
98
- * - `/path/to/database` - local database
99
- * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
100
- * - `db://host:port` - remote database (LanceDB cloud)
101
- * @param options - The options to use when connecting to the database
102
- * @see {@link ConnectionOptions} for more details on the URI format.
103
- * @example
104
- * ```ts
105
- * const conn = await connect({
106
- * uri: "/path/to/database",
107
- * storageOptions: {timeout: "60s"}
108
- * });
109
- * ```
110
- */
111
- export async function connect(
112
- opts: Partial<RemoteConnectionOptions | ConnectionOptions> & { uri: string },
113
- ): Promise<Connection>;
114
- export async function connect(
115
- uriOrOptions:
116
- | string
117
- | (Partial<RemoteConnectionOptions | ConnectionOptions> & { uri: string }),
118
- opts: Partial<ConnectionOptions | RemoteConnectionOptions> = {},
119
- ): Promise<Connection> {
120
- let uri: string | undefined;
121
- if (typeof uriOrOptions !== "string") {
122
- const { uri: uri_, ...options } = uriOrOptions;
123
- uri = uri_;
124
- opts = options;
125
- } else {
126
- uri = uriOrOptions;
127
- }
128
-
129
- if (!uri) {
130
- throw new Error("uri is required");
131
- }
132
-
133
- if (uri?.startsWith("db://")) {
134
- return new RemoteConnection(uri, opts as RemoteConnectionOptions);
135
- }
136
- opts = (opts as ConnectionOptions) ?? {};
137
- (<ConnectionOptions>opts).storageOptions = cleanseStorageOptions(
138
- (<ConnectionOptions>opts).storageOptions,
139
- );
140
- const nativeConn = await LanceDbConnection.new(uri, opts);
141
- return new LocalConnection(nativeConn);
142
- }
@@ -1,203 +0,0 @@
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
-
15
- import { Index as LanceDbIndex } from "./native";
16
-
17
- /**
18
- * Options to create an `IVF_PQ` index
19
- */
20
- export interface IvfPqOptions {
21
- /**
22
- * The number of IVF partitions to create.
23
- *
24
- * This value should generally scale with the number of rows in the dataset.
25
- * By default the number of partitions is the square root of the number of
26
- * rows.
27
- *
28
- * If this value is too large then the first part of the search (picking the
29
- * right partition) will be slow. If this value is too small then the second
30
- * part of the search (searching within a partition) will be slow.
31
- */
32
- numPartitions?: number;
33
-
34
- /**
35
- * Number of sub-vectors of PQ.
36
- *
37
- * This value controls how much the vector is compressed during the quantization step.
38
- * The more sub vectors there are the less the vector is compressed. The default is
39
- * the dimension of the vector divided by 16. If the dimension is not evenly divisible
40
- * by 16 we use the dimension divded by 8.
41
- *
42
- * The above two cases are highly preferred. Having 8 or 16 values per subvector allows
43
- * us to use efficient SIMD instructions.
44
- *
45
- * If the dimension is not visible by 8 then we use 1 subvector. This is not ideal and
46
- * will likely result in poor performance.
47
- */
48
- numSubVectors?: number;
49
-
50
- /**
51
- * Distance type to use to build the index.
52
- *
53
- * Default value is "l2".
54
- *
55
- * This is used when training the index to calculate the IVF partitions
56
- * (vectors are grouped in partitions with similar vectors according to this
57
- * distance type) and to calculate a subvector's code during quantization.
58
- *
59
- * The distance type used to train an index MUST match the distance type used
60
- * to search the index. Failure to do so will yield inaccurate results.
61
- *
62
- * The following distance types are available:
63
- *
64
- * "l2" - Euclidean distance. This is a very common distance metric that
65
- * accounts for both magnitude and direction when determining the distance
66
- * between vectors. L2 distance has a range of [0, ∞).
67
- *
68
- * "cosine" - Cosine distance. Cosine distance is a distance metric
69
- * calculated from the cosine similarity between two vectors. Cosine
70
- * similarity is a measure of similarity between two non-zero vectors of an
71
- * inner product space. It is defined to equal the cosine of the angle
72
- * between them. Unlike L2, the cosine distance is not affected by the
73
- * magnitude of the vectors. Cosine distance has a range of [0, 2].
74
- *
75
- * Note: the cosine distance is undefined when one (or both) of the vectors
76
- * are all zeros (there is no direction). These vectors are invalid and may
77
- * never be returned from a vector search.
78
- *
79
- * "dot" - Dot product. Dot distance is the dot product of two vectors. Dot
80
- * distance has a range of (-∞, ∞). If the vectors are normalized (i.e. their
81
- * L2 norm is 1), then dot distance is equivalent to the cosine distance.
82
- */
83
- distanceType?: "l2" | "cosine" | "dot";
84
-
85
- /**
86
- * Max iteration to train IVF kmeans.
87
- *
88
- * When training an IVF PQ index we use kmeans to calculate the partitions. This parameter
89
- * controls how many iterations of kmeans to run.
90
- *
91
- * Increasing this might improve the quality of the index but in most cases these extra
92
- * iterations have diminishing returns.
93
- *
94
- * The default value is 50.
95
- */
96
- maxIterations?: number;
97
-
98
- /**
99
- * The number of vectors, per partition, to sample when training IVF kmeans.
100
- *
101
- * When an IVF PQ index is trained, we need to calculate partitions. These are groups
102
- * of vectors that are similar to each other. To do this we use an algorithm called kmeans.
103
- *
104
- * Running kmeans on a large dataset can be slow. To speed this up we run kmeans on a
105
- * random sample of the data. This parameter controls the size of the sample. The total
106
- * number of vectors used to train the index is `sample_rate * num_partitions`.
107
- *
108
- * Increasing this value might improve the quality of the index but in most cases the
109
- * default should be sufficient.
110
- *
111
- * The default value is 256.
112
- */
113
- sampleRate?: number;
114
- }
115
-
116
- export class Index {
117
- private readonly inner: LanceDbIndex;
118
- private constructor(inner: LanceDbIndex) {
119
- this.inner = inner;
120
- }
121
-
122
- /**
123
- * Create an IvfPq index
124
- *
125
- * This index stores a compressed (quantized) copy of every vector. These vectors
126
- * are grouped into partitions of similar vectors. Each partition keeps track of
127
- * a centroid which is the average value of all vectors in the group.
128
- *
129
- * During a query the centroids are compared with the query vector to find the closest
130
- * partitions. The compressed vectors in these partitions are then searched to find
131
- * the closest vectors.
132
- *
133
- * The compression scheme is called product quantization. Each vector is divided into
134
- * subvectors and then each subvector is quantized into a small number of bits. the
135
- * parameters `num_bits` and `num_subvectors` control this process, providing a tradeoff
136
- * between index size (and thus search speed) and index accuracy.
137
- *
138
- * The partitioning process is called IVF and the `num_partitions` parameter controls how
139
- * many groups to create.
140
- *
141
- * Note that training an IVF PQ index on a large dataset is a slow operation and
142
- * currently is also a memory intensive operation.
143
- */
144
- static ivfPq(options?: Partial<IvfPqOptions>) {
145
- return new Index(
146
- LanceDbIndex.ivfPq(
147
- options?.distanceType,
148
- options?.numPartitions,
149
- options?.numSubVectors,
150
- options?.maxIterations,
151
- options?.sampleRate,
152
- ),
153
- );
154
- }
155
-
156
- /**
157
- * Create a btree index
158
- *
159
- * A btree index is an index on a scalar columns. The index stores a copy of the column
160
- * in sorted order. A header entry is created for each block of rows (currently the
161
- * block size is fixed at 4096). These header entries are stored in a separate
162
- * cacheable structure (a btree). To search for data the header is used to determine
163
- * which blocks need to be read from disk.
164
- *
165
- * For example, a btree index in a table with 1Bi rows requires sizeof(Scalar) * 256Ki
166
- * bytes of memory and will generally need to read sizeof(Scalar) * 4096 bytes to find
167
- * the correct row ids.
168
- *
169
- * This index is good for scalar columns with mostly distinct values and does best when
170
- * the query is highly selective.
171
- *
172
- * The btree index does not currently have any parameters though parameters such as the
173
- * block size may be added in the future.
174
- */
175
- static btree() {
176
- return new Index(LanceDbIndex.btree());
177
- }
178
- }
179
-
180
- export interface IndexOptions {
181
- /**
182
- * Advanced index configuration
183
- *
184
- * This option allows you to specify a specfic index to create and also
185
- * allows you to pass in configuration for training the index.
186
- *
187
- * See the static methods on Index for details on the various index types.
188
- *
189
- * If this is not supplied then column data type(s) and column statistics
190
- * will be used to determine the most useful kind of index to create.
191
- */
192
- config?: Index;
193
- /**
194
- * Whether to replace the existing index
195
- *
196
- * If this is false, and another index already exists on the same columns
197
- * and the same name, then an error will be returned. This is true even if
198
- * that index is out of date.
199
- *
200
- * The default is true
201
- */
202
- replace?: boolean;
203
- }