mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(query): stream query results with optional total hits (#5354)
## Summary An Embedded query can stream one page of results and report how many visible rows matched before offset and limit. This adds Rust `execute_with_metadata`, Python sync and async `to_result`, and TypeScript `toResult`. The existing query terminals continue to use their existing execution paths. Tracking defaults to Off. An exact count returns `eq(N)`. A positive cap C returns `eq(N)` below C and `gte(C)` as soon as C matches are proven, including equality. TypeScript exposes counts as bigint. Counts use the same snapshot as the result batches. The accessor reports pending until the stream reaches successful EOF. Explicit counts can add work after the last batch, especially when full-text counting needs to scan visible text. Closing an unfinished result cancels execution. Stream and metadata failures retain interruption details, including the request ID. Embedded supports scalar and row-level lexical counts. Unordered FTS retains its existing top-k and scoring policy. Enterprise and unsupported query shapes return a typed error when a count is requested. ## Dependency #5352 merged Lance v16.0.0-beta.7 into main, including [Lance #11680](https://github.com/lance-format/lance/pull/11680). This PR uses that dependency and its lockfiles. ## Validation The Linux-tested revision `bc39ad7ac` and rebased revision `24f4e90c2` have the same Git tree. The only change in `6932b3082` is the Python namespace regression fixture, which now resolves the local table without the optional pylance package. The revised test passed on managed Linux with CPython 3.11.18 both with pylance and pandas installed and after removing both packages. Managed Linux runs used the unmodified manifests and lockfiles from #5352 and the published `pylance 16.0.0b7` wheel. - The Rust metadata suite passed 57 tests, with two existing ignores. Coverage includes unordered FTS plans, top-k scores, physical row addresses under pagination, pending-read cancellation, and interruption after the last batch. - Python query, remote and namespace suites passed 1,163 tests. One optional slow test requires PyTorch, which was unavailable on this VM. The Node query, remote, table and error suites passed 913 tests, with three experimental cases skipped. - Regression tests reproduced the failures on the previous revision and verified the fixes. Python sync reranking and namespace FTS preserve an explicit empty page. Python sync and async scans expose `_rowaddr` alongside the pre-pagination count. Explicit counts are rejected before TypeScript auto-search issues an Enterprise request or invokes a vector embedding provider. Python and Node retain the server's 1,063-row first batch in Off mode. - A custom Python namespace opened through the public API receives the same computed projection in Off mode as with `to_batches()`. A Node result interrupted after another SDK load retains its original error class and request ID. Both regressions were reproduced on the prior revision. - Workspace Clippy, formatting, Ruff, Biome, TypeScript checks, TypeDoc and strict MkDocs passed. All 287 generated TypeDoc files matched the committed files byte for byte.
This commit is contained in:
@@ -3,7 +3,13 @@
|
||||
|
||||
import * as tmp from "tmp";
|
||||
|
||||
import { type Table, connect } from "../lancedb";
|
||||
import {
|
||||
MetadataCancelledError,
|
||||
MetadataPendingError,
|
||||
type Table,
|
||||
UnsupportedMetadataError,
|
||||
connect,
|
||||
} from "../lancedb";
|
||||
import {
|
||||
Field,
|
||||
FixedSizeList,
|
||||
@@ -809,3 +815,75 @@ describe("IVF search effort", () => {
|
||||
).toThrow("search_effort must be finite and in [0, 1]");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Query result metadata", () => {
|
||||
let dir: tmp.DirResult;
|
||||
let table: Table;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = tmp.dirSync({ unsafeCleanup: true });
|
||||
const db = await connect(dir.name);
|
||||
table = await db.createTable("docs", [
|
||||
{ id: 1, text: "cat", vector: [0, 0] },
|
||||
{ id: 2, text: "cat dog", vector: [0, 1] },
|
||||
{ id: 3, text: "dog", vector: [1, 0] },
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => dir.removeCallback());
|
||||
|
||||
it("keeps metadata pending until EOF and retains it after close", async () => {
|
||||
const result = await table
|
||||
.query()
|
||||
.limit(1)
|
||||
.toResult({ trackTotalHits: true });
|
||||
expect((await result.batches.next()).value.numRows).toEqual(1);
|
||||
expect(() => result.metadata()).toThrow(MetadataPendingError);
|
||||
expect(await result.finish()).toEqual({
|
||||
totalHits: { value: 3n, relation: "eq" },
|
||||
});
|
||||
await result.close();
|
||||
expect(result.metadata().totalHits?.value).toEqual(3n);
|
||||
expect(await (await table.query().toResult()).finish()).toEqual({});
|
||||
});
|
||||
|
||||
it("preserves ranking with a capped count and cancels on break", async () => {
|
||||
await table.createIndex("text", { config: Index.fts() });
|
||||
const query = table.query().fullTextSearch("cat dog").limit(1);
|
||||
const capped = await query.toResult({ trackTotalHits: 2n });
|
||||
expect(await capped.finish()).toEqual({
|
||||
totalHits: { value: 2n, relation: "gte" },
|
||||
});
|
||||
const early = await query.toResult({ trackTotalHits: true });
|
||||
for await (const batch of early.batches) {
|
||||
expect(batch.numRows).toEqual(1);
|
||||
break;
|
||||
}
|
||||
expect(() => early.metadata()).toThrow(MetadataCancelledError);
|
||||
await expect(
|
||||
table.vectorSearch([0, 0]).toResult({ trackTotalHits: true }),
|
||||
).rejects.toThrow(UnsupportedMetadataError);
|
||||
});
|
||||
|
||||
it("normalizes threshold boundaries and accepts the largest u64", async () => {
|
||||
const query = table.query().limit(1);
|
||||
for (const [cap, value, relation] of [
|
||||
[2n, 2n, "gte"],
|
||||
[3, 3n, "gte"],
|
||||
[4n, 3n, "eq"],
|
||||
[(1n << 64n) - 1n, 3n, "eq"],
|
||||
] as const) {
|
||||
const result = await query.toResult({ trackTotalHits: cap });
|
||||
expect((await result.finish()).totalHits).toEqual({ value, relation });
|
||||
}
|
||||
});
|
||||
|
||||
it.each([0n, -1, 0.5, Number.MAX_SAFE_INTEGER + 1, 1n << 64n])(
|
||||
"rejects invalid cap %s",
|
||||
async (cap) => {
|
||||
await expect(
|
||||
table.query().toResult({ trackTotalHits: cap }),
|
||||
).rejects.toThrow(RangeError);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -11,10 +11,14 @@ import {
|
||||
Connection,
|
||||
ConnectionOptions,
|
||||
HttpError,
|
||||
LanceError,
|
||||
MetadataCancelledError,
|
||||
MetadataPendingError,
|
||||
OAuthConfig,
|
||||
OAuthFlowType,
|
||||
RetryError,
|
||||
TlsConfig,
|
||||
UnsupportedMetadataError,
|
||||
blob,
|
||||
connect,
|
||||
} from "../lancedb";
|
||||
@@ -29,6 +33,7 @@ import {
|
||||
makeArrowTable,
|
||||
tableToIPC,
|
||||
} from "../lancedb/arrow";
|
||||
import { installLanceErrorTranslation } from "../lancedb/errors";
|
||||
import {
|
||||
HeaderProvider,
|
||||
OAuthHeaderProvider,
|
||||
@@ -38,6 +43,8 @@ import { Index } from "../lancedb/indices";
|
||||
import type { JobProgress } from "../lancedb/job";
|
||||
import { LocalTable } from "../lancedb/table";
|
||||
|
||||
type SdkExports = typeof import("../lancedb");
|
||||
|
||||
// Test-only header providers
|
||||
class CustomProvider extends HeaderProvider {
|
||||
getHeaders(): Record<string, string> {
|
||||
@@ -285,8 +292,10 @@ describe("remote connection", () => {
|
||||
);
|
||||
|
||||
it("reports unsupported operations with backend-neutral errors", async () => {
|
||||
let requests = 0;
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
requests++;
|
||||
expect(req.url).toBe("/v1/table/test/describe/");
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
@@ -311,7 +320,22 @@ describe("remote connection", () => {
|
||||
);
|
||||
},
|
||||
async (db) => {
|
||||
// The second open reuses the server version but starts with a cold schema cache.
|
||||
await db.openTable("test");
|
||||
const table = (await db.openTable("test")) as LocalTable;
|
||||
const requestsAfterOpen = requests;
|
||||
for (const trackTotalHits of [true, 10n]) {
|
||||
for (const query of [
|
||||
table.query(),
|
||||
table.search("dog"),
|
||||
table.search("dog", "vector"),
|
||||
]) {
|
||||
await expect(query.toResult({ trackTotalHits })).rejects.toThrow(
|
||||
UnsupportedMetadataError,
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(requests).toBe(requestsAfterOpen);
|
||||
await expect(table.delta(1)).rejects.toThrow(
|
||||
"table.delta is only supported on LanceDB Embedded tables",
|
||||
);
|
||||
@@ -334,6 +358,79 @@ describe("remote connection", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["interrupted", "closed", "interrupted after SDK reload"])(
|
||||
"preserves the query result terminal state after a batch: %s",
|
||||
async (outcome) => {
|
||||
const serverBatch = makeArrowTable(
|
||||
Array.from({ length: 1063 }, (_, id) => ({ id })),
|
||||
);
|
||||
const ipc = tableToIPC(serverBatch, "stream");
|
||||
let requestId: string | undefined;
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
if (req.url?.endsWith("/describe/")) {
|
||||
res.writeHead(200).end(
|
||||
JSON.stringify({
|
||||
version: 7,
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "double" }, nullable: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else if (req.url?.endsWith("/query/")) {
|
||||
req.resume();
|
||||
requestId = String(req.headers["x-request-id"]);
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/vnd.apache.arrow.stream",
|
||||
"x-lancedb-version": "7",
|
||||
});
|
||||
res.write(ipc.subarray(0, -8));
|
||||
if (outcome !== "closed") res.end();
|
||||
} else {
|
||||
res.writeHead(404).end();
|
||||
}
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("test");
|
||||
const result = await table.query().toResult();
|
||||
expect((await result.next()).value.numRows).toBe(serverBatch.numRows);
|
||||
expect(() => result.metadata()).toThrow(MetadataPendingError);
|
||||
if (outcome === "interrupted after SDK reload") {
|
||||
jest.isolateModules(() => {
|
||||
const reloaded = require("../lancedb") as SdkExports;
|
||||
expect(reloaded.LanceError).not.toBe(LanceError);
|
||||
});
|
||||
}
|
||||
const pending = result.next().finally(() => {
|
||||
if (outcome === "interrupted after SDK reload") {
|
||||
// Restore the shared native prototypes for later tests in this file.
|
||||
installLanceErrorTranslation(require("../lancedb/native.js"));
|
||||
}
|
||||
});
|
||||
if (outcome === "closed") {
|
||||
const cancelled = expect(pending).rejects.toThrow(
|
||||
MetadataCancelledError,
|
||||
);
|
||||
await result.close();
|
||||
await cancelled;
|
||||
expect(() => result.metadata()).toThrow(MetadataCancelledError);
|
||||
} else {
|
||||
await expect(pending).rejects.toBeInstanceOf(LanceError);
|
||||
expect(requestId).toBeTruthy();
|
||||
const details = { code: "ResponseInterrupted", requestId };
|
||||
await expect(pending).rejects.toMatchObject(details);
|
||||
await result.close();
|
||||
expect(() => result.metadata()).toThrow(
|
||||
expect.objectContaining(details),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects nprobes(0) before sending a query", async () => {
|
||||
const requests: string[] = [];
|
||||
await withMockDatabase(
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
TableDelta,
|
||||
TableDeltaReader,
|
||||
TagContents,
|
||||
UnsupportedMetadataError,
|
||||
VectorQuery,
|
||||
blob,
|
||||
connect,
|
||||
@@ -2535,6 +2536,61 @@ describe("automatic search schema consistency", () => {
|
||||
tmpDir.removeCallback();
|
||||
});
|
||||
|
||||
it("rejects explicit counts before preparing embeddings and counts automatic FTS", async () => {
|
||||
const db = await connect(tmpDir.name, { readConsistencyInterval: 0 });
|
||||
const table = await db.createTable("docs", [{ text: "dog" }], {
|
||||
schema: embeddingSchema(),
|
||||
});
|
||||
const parse = jest.spyOn(getRegistry(), "parseFunctions");
|
||||
const embed = jest.spyOn(
|
||||
SchemaRefreshEmbedding.prototype,
|
||||
"computeQueryEmbeddings",
|
||||
);
|
||||
try {
|
||||
const auto = table.search("dog").limit(1);
|
||||
const vector = table.search("dog", "vector").limit(1);
|
||||
for (const query of [auto, vector]) {
|
||||
for (const trackTotalHits of [true, 1n]) {
|
||||
await expect(query.toResult({ trackTotalHits })).rejects.toThrow(
|
||||
UnsupportedMetadataError,
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(parse).not.toHaveBeenCalled();
|
||||
expect(embed).not.toHaveBeenCalled();
|
||||
for (const query of [auto, vector]) {
|
||||
const off = await query.toResult({ trackTotalHits: false });
|
||||
expect((await off.next()).value?.numRows).toBe(1);
|
||||
expect(await off.finish()).toEqual({});
|
||||
expect((await query.toArray())[0].text).toBe("dog");
|
||||
}
|
||||
expect(embed).toHaveBeenCalledTimes(2);
|
||||
|
||||
const replacement = await db.createTable(
|
||||
"docs",
|
||||
[{ text: "dog fish" }, { text: "dog dog" }],
|
||||
{ mode: "overwrite" },
|
||||
);
|
||||
await replacement.createIndex("text", { config: Index.fts() });
|
||||
const exact = await auto.toResult({ trackTotalHits: true });
|
||||
expect((await exact.next()).value?.numRows).toBe(1);
|
||||
expect((await exact.finish()).totalHits).toEqual({
|
||||
value: 2n,
|
||||
relation: "eq",
|
||||
});
|
||||
const capped = await auto.toResult({ trackTotalHits: 1n });
|
||||
expect((await capped.finish()).totalHits).toEqual({
|
||||
value: 1n,
|
||||
relation: "gte",
|
||||
});
|
||||
expect(embed).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
parse.mockRestore();
|
||||
embed.mockRestore();
|
||||
db.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the schema refreshed from another connection", async () => {
|
||||
const first = await connect(tmpDir.name, { readConsistencyInterval: 0 });
|
||||
const second = await connect(tmpDir.name, { readConsistencyInterval: 0 });
|
||||
|
||||
@@ -307,6 +307,11 @@ export class NotSupportedError extends LanceError {
|
||||
static override readonly code = "NotSupported";
|
||||
}
|
||||
|
||||
/** The requested final metadata is unavailable for this query. */
|
||||
export class UnsupportedMetadataError extends LanceError {
|
||||
static override readonly code = "UnsupportedMetadata";
|
||||
}
|
||||
|
||||
/** A local operation exceeded its time limit. */
|
||||
export class TimeoutError extends LanceError {
|
||||
static override readonly code = "Timeout";
|
||||
@@ -400,6 +405,7 @@ const ERROR_CLASSES = new Map<string, LanceErrorConstructor>([
|
||||
["ColumnAlreadyExists", ColumnAlreadyExistsError],
|
||||
["NotAComputedColumn", NotAComputedColumnError],
|
||||
["NotSupported", NotSupportedError],
|
||||
["UnsupportedMetadata", UnsupportedMetadataError],
|
||||
["Timeout", TimeoutError],
|
||||
["Runtime", LanceRuntimeError],
|
||||
["CreateDir", CreateDirError],
|
||||
|
||||
@@ -149,6 +149,14 @@ export type {
|
||||
FunctionProfileWaitOptions,
|
||||
} from "./profiling";
|
||||
|
||||
export {
|
||||
QueryResult,
|
||||
QueryMetadata,
|
||||
TotalHits,
|
||||
MetadataPendingError,
|
||||
MetadataCancelledError,
|
||||
} from "./query_result";
|
||||
|
||||
export {
|
||||
AutoQuery,
|
||||
ExecutableQuery,
|
||||
@@ -282,6 +290,7 @@ export {
|
||||
NotAComputedColumnError,
|
||||
NotAMaterializedViewError,
|
||||
NotSupportedError,
|
||||
UnsupportedMetadataError,
|
||||
ObjectStoreError,
|
||||
OtherError,
|
||||
RetryError,
|
||||
|
||||
+118
-38
@@ -19,7 +19,7 @@ import {
|
||||
vectorFromArray,
|
||||
} from "./arrow";
|
||||
import { isBlobDescriptorField, isBlobField } from "./blob";
|
||||
import { bindErrorTranslator } from "./errors";
|
||||
import { UnsupportedMetadataError, bindErrorTranslator } from "./errors";
|
||||
import { Expr } from "./expr";
|
||||
import { type IvfPqOptions } from "./indices";
|
||||
import {
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
TakeQuery as NativeTakeQuery,
|
||||
VectorQuery as NativeVectorQuery,
|
||||
} from "./native";
|
||||
import { QueryResult, normalizeTrackTotalHits } from "./query_result";
|
||||
import { Reranker } from "./rerankers";
|
||||
|
||||
export async function* RecordBatchIterator(
|
||||
@@ -376,6 +377,8 @@ function addQueryVectorToNative(
|
||||
}
|
||||
}
|
||||
|
||||
type PrepareQuery<T> = (trackTotalHits: boolean) => Promise<T>;
|
||||
|
||||
/** Common methods supported by all query types
|
||||
*
|
||||
* @see {@link Query}
|
||||
@@ -388,6 +391,11 @@ export class QueryBase<
|
||||
> implements AsyncIterable<RecordBatch>
|
||||
{
|
||||
protected inner!: NativeQueryType | Promise<NativeQueryType>;
|
||||
/** @hidden */
|
||||
protected readonly deferred?: {
|
||||
prepare: PrepareQuery<NativeQueryType>;
|
||||
calls: Array<(inner: NativeQueryType) => void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* @hidden
|
||||
@@ -400,8 +408,11 @@ export class QueryBase<
|
||||
protected constructor(
|
||||
inner?: NativeQueryType | Promise<NativeQueryType>,
|
||||
blobContext?: QueryBlobContext,
|
||||
prepare?: PrepareQuery<NativeQueryType>,
|
||||
) {
|
||||
if (inner !== undefined) {
|
||||
if (prepare) {
|
||||
this.deferred = { prepare, calls: [] };
|
||||
} else if (inner !== undefined) {
|
||||
this.setInner(
|
||||
inner instanceof Promise ? inner : bindErrorTranslator(inner),
|
||||
);
|
||||
@@ -423,7 +434,9 @@ export class QueryBase<
|
||||
* @hidden
|
||||
*/
|
||||
protected doCall(fn: (inner: NativeQueryType) => void) {
|
||||
if (this.inner instanceof Promise) {
|
||||
if (this.deferred) {
|
||||
this.deferred.calls.push(fn);
|
||||
} else if (this.inner instanceof Promise) {
|
||||
this.setInner(
|
||||
this.inner.then((inner) => {
|
||||
const bound = bindErrorTranslator(inner);
|
||||
@@ -441,7 +454,15 @@ export class QueryBase<
|
||||
*
|
||||
* @hidden
|
||||
*/
|
||||
protected async getInner(): Promise<NativeQueryType> {
|
||||
protected async getInner(trackTotalHits = false): Promise<NativeQueryType> {
|
||||
if (this.deferred) {
|
||||
const calls = [...this.deferred.calls];
|
||||
const inner = bindErrorTranslator(
|
||||
await this.deferred.prepare(trackTotalHits),
|
||||
);
|
||||
for (const call of calls) call(inner);
|
||||
return inner;
|
||||
}
|
||||
return this.inner;
|
||||
}
|
||||
|
||||
@@ -566,6 +587,40 @@ export class QueryBase<
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream one execution and read its metadata after successful exhaustion.
|
||||
* Tracking is off by default. Set `trackTotalHits` to `true` for an exact count
|
||||
* before offset and limit, or to a positive integer for a capped count.
|
||||
* At the cap, `totalHits.relation` is `"gte"`.
|
||||
*
|
||||
* Embedded supports counts for unfiltered scans, scans with deterministic scalar
|
||||
* filters, and row-level full-text searches for a single term or a positive OR
|
||||
* of terms with supported prefilters. Requesting a count on an Enterprise table
|
||||
* or an unsupported query, such as vector or hybrid search, throws
|
||||
* `UnsupportedMetadataError`.
|
||||
*
|
||||
* Counting can continue after the last data batch. Consume the iterator to EOF
|
||||
* or await `result.finish()` before calling `result.metadata()`.
|
||||
*
|
||||
* @example
|
||||
* const result = await table.query().limit(1).toResult({ trackTotalHits: 100n });
|
||||
* const hits = (await result.finish()).totalHits;
|
||||
*/
|
||||
async toResult(options?: {
|
||||
trackTotalHits?: boolean | number | bigint;
|
||||
}): Promise<QueryResult> {
|
||||
for (const field of Object.keys(options ?? {})) {
|
||||
if (field !== "trackTotalHits") {
|
||||
throw new UnsupportedMetadataError(
|
||||
`Unknown query metadata option: ${field}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const [track, cap] = normalizeTrackTotalHits(options?.trackTotalHits);
|
||||
const query = await this.getInner(track);
|
||||
return new QueryResult(await query.executeWithMetadata(track, cap));
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query and return the results as an @see {@link AsyncIterator}
|
||||
* of @see {@link RecordBatch}.
|
||||
@@ -774,8 +829,9 @@ export class StandardQueryBase<
|
||||
constructor(
|
||||
inner?: NativeQueryType | Promise<NativeQueryType>,
|
||||
blobContext?: QueryBlobContext,
|
||||
prepare?: PrepareQuery<NativeQueryType>,
|
||||
) {
|
||||
super(inner, blobContext);
|
||||
super(inner, blobContext, prepare);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -962,10 +1018,25 @@ export class VectorQuery extends StandardQueryBase<NativeVectorQuery> {
|
||||
* @hidden
|
||||
*/
|
||||
constructor(
|
||||
inner: NativeVectorQuery | Promise<NativeVectorQuery>,
|
||||
inner:
|
||||
| NativeVectorQuery
|
||||
| Promise<NativeVectorQuery>
|
||||
| PrepareQuery<NativeVectorQuery>,
|
||||
blobContext?: QueryBlobContext,
|
||||
) {
|
||||
super(inner, blobContext);
|
||||
super(
|
||||
typeof inner === "function" ? undefined : inner,
|
||||
blobContext,
|
||||
typeof inner === "function" ? inner : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
/** @hidden */
|
||||
protected override async getInner(
|
||||
trackTotalHits = false,
|
||||
): Promise<NativeVectorQuery> {
|
||||
if (trackTotalHits) throw unsupportedVectorMetadata();
|
||||
return super.getInner();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1234,7 +1305,7 @@ export class VectorQuery extends StandardQueryBase<NativeVectorQuery> {
|
||||
(value) => ({ status: "fulfilled" as const, value }),
|
||||
(reason) => ({ status: "rejected" as const, reason }),
|
||||
);
|
||||
const res = (async () => {
|
||||
const prepare = async () => {
|
||||
const inner = await this.getInner();
|
||||
const outcome = await settledVector;
|
||||
if (outcome.status === "rejected") {
|
||||
@@ -1242,8 +1313,13 @@ export class VectorQuery extends StandardQueryBase<NativeVectorQuery> {
|
||||
}
|
||||
addQueryVectorToNative(inner, outcome.value);
|
||||
return inner;
|
||||
})();
|
||||
return new VectorQuery(res, this.blobContext);
|
||||
};
|
||||
// A string vector search may still need to call an embedding provider.
|
||||
// Keep that work behind the terminal operation even for batch queries.
|
||||
return new VectorQuery(
|
||||
this.deferred ? prepare : prepare(),
|
||||
this.blobContext,
|
||||
);
|
||||
} else {
|
||||
this.doVectorCall((inner) => addQueryVectorToNative(inner, vector));
|
||||
return this;
|
||||
@@ -1325,7 +1401,14 @@ export function createAutoQuery(
|
||||
};
|
||||
};
|
||||
|
||||
const createInner = async (): Promise<NativeQuery | NativeVectorQuery> => {
|
||||
const createInner = async (
|
||||
trackTotalHits: boolean,
|
||||
): Promise<NativeQuery | NativeVectorQuery> => {
|
||||
if (trackTotalHits && !table.isNative()) {
|
||||
throw new UnsupportedMetadataError(
|
||||
"total_hits is unavailable on Enterprise tables",
|
||||
);
|
||||
}
|
||||
const route = await snapshotRoute();
|
||||
if (route.embeddingMetadata === undefined) {
|
||||
const inner = route.table.query();
|
||||
@@ -1333,6 +1416,7 @@ export function createAutoQuery(
|
||||
return inner;
|
||||
}
|
||||
|
||||
if (trackTotalHits) throw unsupportedVectorMetadata();
|
||||
const metadata = route.embeddingMetadata;
|
||||
if (cachedPreparation?.metadata !== metadata) {
|
||||
cachedPreparation = {
|
||||
@@ -1358,6 +1442,27 @@ export function createAutoQuery(
|
||||
return new AutoQuery(createInner, { table, withRowId: false });
|
||||
}
|
||||
|
||||
function unsupportedVectorMetadata(): UnsupportedMetadataError {
|
||||
return new UnsupportedMetadataError(
|
||||
"total_hits is unavailable for vector search",
|
||||
);
|
||||
}
|
||||
|
||||
/** @hidden */
|
||||
export function createEmbeddingQuery(
|
||||
table: NativeTable,
|
||||
getVector: () => Promise<Awaited<IntoVector>>,
|
||||
): VectorQuery {
|
||||
let vector: Promise<Awaited<IntoVector>> | undefined;
|
||||
return new VectorQuery(
|
||||
async () => {
|
||||
vector ??= getVector();
|
||||
return nearestToNative(table.query(), await vector);
|
||||
},
|
||||
{ table, withRowId: false },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A query that returns a subset of the rows in the table.
|
||||
*
|
||||
@@ -1395,37 +1500,12 @@ export class TakeQuery extends QueryBase<NativeTakeQuery> {
|
||||
export class AutoQuery extends StandardQueryBase<
|
||||
NativeQuery | NativeVectorQuery
|
||||
> {
|
||||
private readonly calls: Array<
|
||||
(inner: NativeQuery | NativeVectorQuery) => void
|
||||
> = [];
|
||||
|
||||
/** @hidden */
|
||||
constructor(
|
||||
private readonly createInner: () => Promise<
|
||||
NativeQuery | NativeVectorQuery
|
||||
>,
|
||||
createInner: PrepareQuery<NativeQuery | NativeVectorQuery>,
|
||||
blobContext?: QueryBlobContext,
|
||||
) {
|
||||
super(undefined, blobContext);
|
||||
}
|
||||
|
||||
/** @hidden */
|
||||
protected override doCall(
|
||||
fn: (inner: NativeQuery | NativeVectorQuery) => void,
|
||||
) {
|
||||
this.calls.push(fn);
|
||||
}
|
||||
|
||||
/** @hidden */
|
||||
protected override async getInner(): Promise<
|
||||
NativeQuery | NativeVectorQuery
|
||||
> {
|
||||
const calls = [...this.calls];
|
||||
const inner = await this.createInner();
|
||||
for (const call of calls) {
|
||||
call(inner);
|
||||
}
|
||||
return inner;
|
||||
super(undefined, blobContext, createInner);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { type RecordBatch, tableFromIPC } from "./arrow";
|
||||
import { bindErrorTranslator, materializeLanceError } from "./errors";
|
||||
import type { NativeQueryResult } from "./native";
|
||||
|
||||
export interface TotalHits {
|
||||
readonly value: bigint;
|
||||
readonly relation: "eq" | "gte";
|
||||
}
|
||||
|
||||
export interface QueryMetadata {
|
||||
readonly totalHits?: TotalHits;
|
||||
}
|
||||
|
||||
export class MetadataPendingError extends Error {}
|
||||
export class MetadataCancelledError extends Error {}
|
||||
|
||||
/** @hidden */
|
||||
export function normalizeTrackTotalHits(
|
||||
value: boolean | number | bigint = false,
|
||||
): [boolean, bigint?] {
|
||||
if (typeof value === "boolean") return [value];
|
||||
if (typeof value === "number" && Number.isSafeInteger(value)) {
|
||||
value = BigInt(value);
|
||||
}
|
||||
if (
|
||||
typeof value !== "bigint" ||
|
||||
value <= 0n ||
|
||||
value > 0xffff_ffff_ffff_ffffn
|
||||
) {
|
||||
throw new RangeError(
|
||||
"trackTotalHits must be a boolean, positive safe integer, or positive u64 bigint",
|
||||
);
|
||||
}
|
||||
return [true, value];
|
||||
}
|
||||
|
||||
/** One execution with pull-driven batches and final metadata. */
|
||||
export class QueryResult implements AsyncIterableIterator<RecordBatch> {
|
||||
private finalMetadata?: QueryMetadata;
|
||||
private failure?: Error;
|
||||
private reading = false;
|
||||
|
||||
/** @hidden */
|
||||
constructor(private readonly native: NativeQueryResult) {
|
||||
bindErrorTranslator(native);
|
||||
}
|
||||
|
||||
get batches(): AsyncIterableIterator<RecordBatch> {
|
||||
return this;
|
||||
}
|
||||
|
||||
[Symbol.asyncIterator](): AsyncIterableIterator<RecordBatch> {
|
||||
return this;
|
||||
}
|
||||
|
||||
async next(): Promise<IteratorResult<RecordBatch>> {
|
||||
if (this.failure) throw this.failure;
|
||||
if (this.finalMetadata) return { done: true, value: undefined };
|
||||
if (this.reading) throw new Error("A batch read is already in progress");
|
||||
this.reading = true;
|
||||
try {
|
||||
const buffer = await this.native.nextBatch();
|
||||
if (this.failure) throw this.failure;
|
||||
if (buffer) {
|
||||
const { batches } = tableFromIPC(buffer);
|
||||
if (batches.length !== 1) throw new Error("Expected one Arrow batch");
|
||||
return { done: false, value: batches[0] };
|
||||
}
|
||||
const hits = this.native.totalHits();
|
||||
if (hits && hits.relation !== "eq" && hits.relation !== "gte") {
|
||||
throw new Error("Unknown total_hits relation");
|
||||
}
|
||||
this.finalMetadata = hits
|
||||
? {
|
||||
totalHits: {
|
||||
value: hits.value,
|
||||
relation: hits.relation as "eq" | "gte",
|
||||
},
|
||||
}
|
||||
: {};
|
||||
return { done: true, value: undefined };
|
||||
} catch (error) {
|
||||
const failure = materializeLanceError(error);
|
||||
this.failure ??=
|
||||
failure instanceof Error ? failure : new Error(String(failure));
|
||||
await this.native.close();
|
||||
throw this.failure;
|
||||
} finally {
|
||||
this.reading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Access the successful terminal metadata without polling the stream. */
|
||||
metadata(): QueryMetadata {
|
||||
if (this.failure) throw this.failure;
|
||||
if (!this.finalMetadata)
|
||||
throw new MetadataPendingError("Query metadata is pending until EOF");
|
||||
return this.finalMetadata;
|
||||
}
|
||||
|
||||
async finish(): Promise<QueryMetadata> {
|
||||
while (!(await this.next()).done) {
|
||||
// Discard each remaining batch.
|
||||
}
|
||||
return this.metadata();
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (!this.finalMetadata && !this.failure) {
|
||||
this.failure = new MetadataCancelledError(
|
||||
"Query result was closed before EOF",
|
||||
);
|
||||
}
|
||||
await this.native.close();
|
||||
}
|
||||
|
||||
async return(): Promise<IteratorResult<RecordBatch>> {
|
||||
await this.close();
|
||||
return { done: true, value: undefined };
|
||||
}
|
||||
}
|
||||
+12
-16
@@ -178,6 +178,7 @@ import {
|
||||
TakeQuery,
|
||||
VectorQuery,
|
||||
createAutoQuery,
|
||||
createEmbeddingQuery,
|
||||
instanceOfFullTextQuery,
|
||||
} from "./query";
|
||||
import { sanitizeSchema, sanitizeType } from "./sanitize";
|
||||
@@ -2147,22 +2148,17 @@ export class LocalTable extends Table {
|
||||
});
|
||||
}
|
||||
|
||||
const queryPromise = this.getEmbeddingFunctions().then(
|
||||
async (functions) => {
|
||||
// TODO: Support multiple embedding functions
|
||||
const embeddingFunc: EmbeddingFunctionConfig | undefined = functions
|
||||
.values()
|
||||
.next().value;
|
||||
if (!embeddingFunc) {
|
||||
return Promise.reject(
|
||||
new Error("No embedding functions are defined in the table"),
|
||||
);
|
||||
}
|
||||
return await embeddingFunc.function.computeQueryEmbeddings(query);
|
||||
},
|
||||
);
|
||||
|
||||
return this.query().nearestTo(queryPromise);
|
||||
return createEmbeddingQuery(this.inner, async () => {
|
||||
const functions = await this.getEmbeddingFunctions();
|
||||
// TODO: Support multiple embedding functions
|
||||
const embeddingFunc: EmbeddingFunctionConfig | undefined = functions
|
||||
.values()
|
||||
.next().value;
|
||||
if (!embeddingFunc) {
|
||||
throw new Error("No embedding functions are defined in the table");
|
||||
}
|
||||
return await embeddingFunc.function.computeQueryEmbeddings(query);
|
||||
});
|
||||
}
|
||||
|
||||
vectorSearch(vector: IntoVector | MultiVector): VectorQuery {
|
||||
|
||||
@@ -75,6 +75,7 @@ fn error_payload(err: &LanceError) -> String {
|
||||
|
||||
fn error_code(err: &LanceError) -> &'static str {
|
||||
match err {
|
||||
err if err.unsupported_metadata().is_some() => "UnsupportedMetadata",
|
||||
LanceError::InvalidTableName { .. } => "InvalidTableName",
|
||||
LanceError::InvalidInput { .. } => "InvalidInput",
|
||||
LanceError::TableNotFound { .. } => "TableNotFound",
|
||||
|
||||
@@ -42,3 +42,58 @@ impl RecordBatchIterator {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pull-driven result with interruptible reads and a final count.
|
||||
#[napi]
|
||||
pub struct NativeQueryResult {
|
||||
reader: lancedb::query::metadata_reader::QueryResultReader,
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct NativeTotalHits {
|
||||
pub value: BigInt,
|
||||
pub relation: String,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl NativeQueryResult {
|
||||
pub(crate) fn new(result: lancedb::query::QueryResult) -> Self {
|
||||
Self {
|
||||
reader: lancedb::query::metadata_reader::QueryResultReader::new(result),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn next_batch(&self) -> napi::Result<Option<Buffer>> {
|
||||
let batch = self
|
||||
.reader
|
||||
.next()
|
||||
.await
|
||||
.map_err(|e| crate::error::convert_error(&e))?;
|
||||
batch
|
||||
.map(|b| {
|
||||
batches_to_ipc_file(&[b])
|
||||
.map(Buffer::from)
|
||||
.map_err(|e| crate::error::convert_error(&e))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn total_hits(&self) -> napi::Result<Option<NativeTotalHits>> {
|
||||
let metadata = self
|
||||
.reader
|
||||
.metadata()
|
||||
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
|
||||
Ok(metadata.total_hits.as_ref().map(|hits| NativeTotalHits {
|
||||
value: BigInt::from(hits.value),
|
||||
relation: hits.relation.as_str().into(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn close(&self) -> napi::Result<()> {
|
||||
self.reader.close().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+67
-1
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
|
||||
use crate::error::NapiErrorExt;
|
||||
use crate::error::convert_error;
|
||||
use crate::iterator::RecordBatchIterator;
|
||||
use crate::iterator::{NativeQueryResult, RecordBatchIterator};
|
||||
use crate::rerankers::{RerankHybridCallbackArgs, RerankVectorCallbackArgs, Reranker};
|
||||
use crate::util::{parse_distance_type, schema_to_buffer};
|
||||
use arrow_array::{
|
||||
@@ -48,6 +48,25 @@ impl From<ColumnOrdering> for LanceDbColumnOrdering {
|
||||
}
|
||||
}
|
||||
|
||||
fn metadata_request(
|
||||
track: bool,
|
||||
cap: Option<BigInt>,
|
||||
) -> napi::Result<lancedb::query::MetadataRequest> {
|
||||
use lancedb::query::{MetadataRequest, TrackTotalHits};
|
||||
let mode = if let Some(cap) = cap {
|
||||
let (negative, value, lossless) = cap.get_u64();
|
||||
let cap = std::num::NonZeroU64::new(value)
|
||||
.filter(|_| !negative && lossless)
|
||||
.ok_or_else(|| napi::Error::from_reason("trackTotalHits must be a positive u64"))?;
|
||||
TrackTotalHits::UpTo(cap)
|
||||
} else if track {
|
||||
TrackTotalHits::Exact
|
||||
} else {
|
||||
TrackTotalHits::Off
|
||||
};
|
||||
Ok(MetadataRequest::new().track_total_hits(mode))
|
||||
}
|
||||
|
||||
fn analyze_plan_options(
|
||||
distributed_metrics: Option<String>,
|
||||
) -> napi::Result<QueryExecutionOptions> {
|
||||
@@ -196,6 +215,22 @@ impl Query {
|
||||
schema_to_buffer(&schema)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn execute_with_metadata(
|
||||
&self,
|
||||
track: bool,
|
||||
cap: Option<BigInt>,
|
||||
) -> napi::Result<NativeQueryResult> {
|
||||
let request = metadata_request(track, cap)?;
|
||||
let options = QueryExecutionOptions::default().with_optional_max_batch_length(None);
|
||||
let result = self
|
||||
.inner
|
||||
.execute_with_metadata(options, request)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(NativeQueryResult::new(result))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn execute(
|
||||
&self,
|
||||
@@ -437,6 +472,22 @@ impl VectorQuery {
|
||||
schema_to_buffer(&schema)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn execute_with_metadata(
|
||||
&self,
|
||||
track: bool,
|
||||
cap: Option<BigInt>,
|
||||
) -> napi::Result<NativeQueryResult> {
|
||||
let request = metadata_request(track, cap)?;
|
||||
let options = QueryExecutionOptions::default().with_optional_max_batch_length(None);
|
||||
let result = self
|
||||
.inner
|
||||
.execute_with_metadata(options, request)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(NativeQueryResult::new(result))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn execute(
|
||||
&self,
|
||||
@@ -516,6 +567,21 @@ impl TakeQuery {
|
||||
schema_to_buffer(&schema)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn execute_with_metadata(
|
||||
&self,
|
||||
track: bool,
|
||||
cap: Option<BigInt>,
|
||||
) -> napi::Result<NativeQueryResult> {
|
||||
let request = metadata_request(track, cap)?;
|
||||
let result = self
|
||||
.inner
|
||||
.execute_with_metadata(Default::default(), request)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(NativeQueryResult::new(result))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn execute(
|
||||
&self,
|
||||
|
||||
Reference in New Issue
Block a user