diff --git a/docs/src/js/classes/Index.md b/docs/src/js/classes/Index.md index d76acaa3c..77105443e 100644 --- a/docs/src/js/classes/Index.md +++ b/docs/src/js/classes/Index.md @@ -27,6 +27,39 @@ is small (i.e., less than a few hundreds). *** +### bloomFilter() + +```ts +static bloomFilter(options?): Index +``` + +Create a Bloom filter index. + +Bloom filters accelerate equality and membership filters by skipping groups +of rows that cannot match. Candidate rows are checked to remove false +positives. This index uses less space than a btree or bitmap index, but does +not accelerate range filters. Unset options use Lance's defaults. + +#### Parameters + +* **options?**: [`BloomFilterOptions`](../interfaces/BloomFilterOptions.md) + +#### Returns + +[`Index`](Index.md) + +#### Example + +Tuning a Bloom filter on an Embedded table: + +```ts +await table.createIndex("id", { + config: Index.bloomFilter({ numberOfItems: 4096, probability: 0.01 }), +}); +``` + +*** + ### btree() ```ts @@ -349,3 +382,38 @@ await table .where("ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))") .toArray(); ``` + +*** + +### zoneMap() + +```ts +static zoneMap(): Index +``` + +Create a ZoneMap index. + +This index stores min/max summaries for ranges of rows and skips ranges that +cannot match a filter. It works best for numeric or temporal columns whose +values are correlated with row order, such as timestamps or sequential IDs. + +For strings, binary data, and supported types wider than eight bytes, this +index uses per-fragment write seeds. By default, these use version 0 and do +not activate the version 1 table capability. + +A commit that explicitly sets the table configuration key +`lance.zone_write_seeds.version` to `"1"` activates a persistent reader and +writer capability. Upgrade all readers and writers before opting in: clients +that do not support this capability cannot access the resulting snapshots. +Dropping the index or restoring an older version does not remove the +capability from subsequent snapshots. + +#### Returns + +[`Index`](Index.md) + +#### Example + +```ts +await table.createIndex("timestamp", { config: Index.zoneMap() }); +``` diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index e98ddccaf..c2a15f5a5 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -65,6 +65,7 @@ - [AlterColumnsResult](interfaces/AlterColumnsResult.md) - [BlobDescriptor](interfaces/BlobDescriptor.md) - [BlobDescriptorSource](interfaces/BlobDescriptorSource.md) +- [BloomFilterOptions](interfaces/BloomFilterOptions.md) - [BranchColumnChange](interfaces/BranchColumnChange.md) - [BranchColumnSummary](interfaces/BranchColumnSummary.md) - [BranchDiff](interfaces/BranchDiff.md) diff --git a/docs/src/js/interfaces/BloomFilterOptions.md b/docs/src/js/interfaces/BloomFilterOptions.md new file mode 100644 index 000000000..29a8ab0b1 --- /dev/null +++ b/docs/src/js/interfaces/BloomFilterOptions.md @@ -0,0 +1,36 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BloomFilterOptions + +# Interface: BloomFilterOptions + +Options to create a Bloom filter index. + +## Properties + +### numberOfItems? + +```ts +optional numberOfItems: number; +``` + +The number of rows covered by each Bloom filter. Must be a positive safe integer. + +Defaults to 8192, unless overridden by Lance's +`LANCE_BLOOMFILTER_DEFAULT_NUMBER_OF_ITEMS` environment variable. + +*** + +### probability? + +```ts +optional probability: number; +``` + +The desired false-positive probability. Must be finite and strictly between zero and one. +Lower values use more space. + +Defaults to 0.00057, unless overridden by Lance's +`LANCE_BLOOMFILTER_DEFAULT_PROBABILITY` environment variable. diff --git a/nodejs/__test__/indices.test.ts b/nodejs/__test__/indices.test.ts new file mode 100644 index 000000000..68f5c409f --- /dev/null +++ b/nodejs/__test__/indices.test.ts @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { type BloomFilterOptions, Index } from "../lancedb"; + +describe("BloomFilter options", () => { + it.each([ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + ])("rejects invalid numberOfItems %s", (numberOfItems) => { + expect(() => Index.bloomFilter({ numberOfItems })).toThrow( + "numberOfItems must be a positive safe integer", + ); + }); + + it.each([ + -0.1, + 0, + 1, + 1.1, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + ])("rejects invalid probability %s", (probability) => { + expect(() => Index.bloomFilter({ probability })).toThrow( + "probability must be finite and strictly between zero and one", + ); + }); + + it.each([ + {}, + { numberOfItems: 1 }, + { numberOfItems: Number.MAX_SAFE_INTEGER }, + { probability: Number.MIN_VALUE }, + { probability: 1 - Number.EPSILON }, + ])("accepts valid options %j", (options) => { + expect(() => Index.bloomFilter(options)).not.toThrow(); + }); +}); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 8844afcf2..68a4ad9cd 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2015,6 +2015,79 @@ describe("remote connection", () => { ]); }); + it.each([ + ["ZoneMap", () => Index.zoneMap(), { ["index_type"]: "ZONEMAP" }], + [ + "default BloomFilter", + () => Index.bloomFilter(), + { ["index_type"]: "BLOOM_FILTER" }, + ], + [ + "BloomFilter numberOfItems", + () => Index.bloomFilter({ numberOfItems: 64 }), + { ["index_type"]: "BLOOM_FILTER", ["number_of_items"]: 64 }, + ], + [ + "BloomFilter probability", + () => Index.bloomFilter({ probability: 0.01 }), + { ["index_type"]: "BLOOM_FILTER", probability: 0.01 }, + ], + [ + "custom BloomFilter", + () => Index.bloomFilter({ numberOfItems: 64, probability: 0.01 }), + { + ["index_type"]: "BLOOM_FILTER", + ["number_of_items"]: 64, + probability: 0.01, + }, + ], + [ + "BloomFilter with a large numberOfItems", + () => Index.bloomFilter({ numberOfItems: Number.MAX_SAFE_INTEGER }), + { + ["index_type"]: "BLOOM_FILTER", + ["number_of_items"]: Number.MAX_SAFE_INTEGER, + }, + ], + ])("sends %s options to remote tables", async (_, config, expected) => { + let createIndexBody: Record | undefined; + + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "t", + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: false }, + ], + }, + }), + ); + } else if (req.url?.endsWith("/create_index/")) { + let raw = ""; + req.on("data", (chunk) => { + raw += chunk; + }); + req.on("end", () => { + createIndexBody = JSON.parse(raw); + res.writeHead(200).end(); + }); + } else { + res.writeHead(404).end(); + } + }, + async (db) => { + const table = await db.openTable("t"); + await table.createIndex("id", { config: config() }); + }, + ); + + expect(createIndexBody).toEqual({ column: "id", ...expected }); + }); + it("diffs and cherry-picks remote branches", async () => { const sampleDiff = { fromBranch: "exp", diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 1f9628348..e712b59e7 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -1794,6 +1794,41 @@ describe("When creating an index", () => { expect(fs.readdirSync(indexDir)).toHaveLength(1); }); + test("create a ZoneMap index and use it for range filters", async () => { + await tbl.createIndex("id", { config: Index.zoneMap() }); + expect(await tbl.listIndices()).toEqual([ + expect.objectContaining({ + indexType: "ZoneMap", + columns: ["id"], + }), + ]); + + const query = tbl.query().where("id >= 100 AND id < 110").select(["id"]); + expect(await query.explainPlan(true)).toContain("ScalarIndexQuery"); + expect( + (await query.toArray()).map((row) => row.id).sort((a, b) => a - b), + ).toEqual(Array.from({ length: 10 }, (_, i) => i + 100)); + }); + + test.each([ + ["default", undefined], + ["custom", { numberOfItems: 64, probability: 0.01 }], + ])("create a BloomFilter index with %s options", async (_, options) => { + await tbl.createIndex("id", { config: Index.bloomFilter(options) }); + expect(await tbl.listIndices()).toEqual([ + expect.objectContaining({ + indexType: "BloomFilter", + columns: ["id"], + }), + ]); + + const query = tbl.query().where("id IN (42, 142, 999)").select(["id"]); + expect(await query.explainPlan(true)).toContain("ScalarIndexQuery"); + expect( + (await query.toArray()).map((row) => row.id).sort((a, b) => a - b), + ).toEqual([42, 142]); + }); + test("create a hnswPq index", async () => { await tbl.createIndex("vec", { config: Index.hnswPq({ diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 58e1f0cde..cbce5cf4a 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -178,6 +178,7 @@ export { IvfFlatOptions, HnswPqOptions, HnswSqOptions, + BloomFilterOptions, FtsOptions, RTreeOptions, BaseTokenizer, diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index 23536bb07..4d91ffc8f 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -580,6 +580,28 @@ export type BaseTokenizer = | `jieba/${string}` | `lindera/${string}`; +/** + * Options to create a Bloom filter index. + */ +export interface BloomFilterOptions { + /** + * The number of rows covered by each Bloom filter. Must be a positive safe integer. + * + * Defaults to 8192, unless overridden by Lance's + * `LANCE_BLOOMFILTER_DEFAULT_NUMBER_OF_ITEMS` environment variable. + */ + numberOfItems?: number; + + /** + * The desired false-positive probability. Must be finite and strictly between zero and one. + * Lower values use more space. + * + * Defaults to 0.00057, unless overridden by Lance's + * `LANCE_BLOOMFILTER_DEFAULT_PROBABILITY` environment variable. + */ + probability?: number; +} + /** * Options to create a full text search index */ @@ -924,6 +946,56 @@ export class Index { return new Index(LanceDbIndex.plugin(indexType, paramsJson)); } + /** + * Create a ZoneMap index. + * + * This index stores min/max summaries for ranges of rows and skips ranges that + * cannot match a filter. It works best for numeric or temporal columns whose + * values are correlated with row order, such as timestamps or sequential IDs. + * + * For strings, binary data, and supported types wider than eight bytes, this + * index uses per-fragment write seeds. By default, these use version 0 and do + * not activate the version 1 table capability. + * + * A commit that explicitly sets the table configuration key + * `lance.zone_write_seeds.version` to `"1"` activates a persistent reader and + * writer capability. Upgrade all readers and writers before opting in: clients + * that do not support this capability cannot access the resulting snapshots. + * Dropping the index or restoring an older version does not remove the + * capability from subsequent snapshots. + * + * @example + * ```ts + * await table.createIndex("timestamp", { config: Index.zoneMap() }); + * ``` + */ + static zoneMap() { + return new Index(LanceDbIndex.zoneMap()); + } + + /** + * Create a Bloom filter index. + * + * Bloom filters accelerate equality and membership filters by skipping groups + * of rows that cannot match. Candidate rows are checked to remove false + * positives. This index uses less space than a btree or bitmap index, but does + * not accelerate range filters. Unset options use Lance's defaults. + * + * @example + * Tuning a Bloom filter on an Embedded table: + * + * ```ts + * await table.createIndex("id", { + * config: Index.bloomFilter({ numberOfItems: 4096, probability: 0.01 }), + * }); + * ``` + */ + static bloomFilter(options?: BloomFilterOptions) { + return new Index( + LanceDbIndex.bloomFilter(options?.numberOfItems, options?.probability), + ); + } + /** * Create a full text search index * diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs index 638d4856f..e1f888f78 100644 --- a/nodejs/src/index.rs +++ b/nodejs/src/index.rs @@ -5,7 +5,8 @@ use std::sync::Mutex; use lancedb::index::Index as LanceDbIndex; use lancedb::index::scalar::{ - BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, PluginIndexBuilder, RTreeIndexBuilder, + BTreeIndexBuilder, BloomFilterIndexBuilder, FmIndexBuilder, FtsIndexBuilder, + PluginIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder, }; use lancedb::index::vector::{ IvfFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder, @@ -251,6 +252,42 @@ impl Index { }) } + /// Create a ZoneMap index using the defaults in [`ZoneMapIndexBuilder`]. + #[napi(factory)] + pub fn zone_map() -> Self { + Self { + inner: Mutex::new(Some(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default()))), + } + } + + /// Create a Bloom filter index with validated [`BloomFilterIndexBuilder`] options. + #[napi(factory)] + pub fn bloom_filter( + number_of_items: Option, + probability: Option, + ) -> napi::Result { + let mut opts = BloomFilterIndexBuilder::default(); + if let Some(number_of_items) = number_of_items { + // JavaScript numbers must be losslessly representable before conversion to u64. + if number_of_items.fract() != 0.0 + || !(1.0..=9_007_199_254_740_991.0).contains(&number_of_items) + { + return Err(napi::Error::from_reason( + "BloomFilter numberOfItems must be a positive safe integer", + )); + } + opts = opts + .number_of_items(number_of_items as u64) + .default_error()?; + } + if let Some(probability) = probability { + opts = opts.probability(probability).default_error()?; + } + Ok(Self { + inner: Mutex::new(Some(LanceDbIndex::BloomFilter(opts))), + }) + } + #[napi(factory)] #[allow(clippy::too_many_arguments)] pub fn fts(