mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat: support vector-only and FTS-only reranking (#3024)
Add rerank_vector() and rerank_fts() methods to Reranker trait, allowing rerankers to work with single search modes instead of only hybrid search. Implemented for: - RRFReranker (Rust and Python) - LinearCombinationReranker (Python) Resolves TODO at rust/lancedb/src/rerankers.rs:55 Changes: - Extended Reranker trait with default implementations - Added unit tests for new methods - Updated documentation with examples --------- Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
@@ -668,6 +668,8 @@ distance between the query vector and the actual uncompressed vector.
|
||||
rerank(reranker): VectorQuery
|
||||
```
|
||||
|
||||
Apply a reranker to this vector or hybrid query.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **reranker**: [`Reranker`](../namespaces/rerankers/interfaces/Reranker.md)
|
||||
|
||||
@@ -33,6 +33,26 @@ rerankHybrid(
|
||||
|
||||
***
|
||||
|
||||
### rerankVector()
|
||||
|
||||
```ts
|
||||
rerankVector(query, results): Promise<RecordBatch<any>>
|
||||
```
|
||||
|
||||
Score vector search results by their one-based rank.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **query**: `string`
|
||||
|
||||
* **results**: `RecordBatch`<`any`>
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`RecordBatch`<`any`>>
|
||||
|
||||
***
|
||||
|
||||
### create()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -6,8 +6,29 @@
|
||||
|
||||
# Interface: Reranker
|
||||
|
||||
Reranks vector or hybrid search results.
|
||||
|
||||
## Methods
|
||||
|
||||
### outputSchema()?
|
||||
|
||||
```ts
|
||||
optional outputSchema(input): Schema<any> | Promise<Schema<any>>
|
||||
```
|
||||
|
||||
Declare the output fields for vector reranking. The default keeps the
|
||||
input fields and appends a non-nullable Float32 `_relevance_score` field.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **input**: `Schema`<`any`>
|
||||
|
||||
#### Returns
|
||||
|
||||
`Schema`<`any`> \| `Promise`<`Schema`<`any`>>
|
||||
|
||||
***
|
||||
|
||||
### rerankHybrid()
|
||||
|
||||
```ts
|
||||
@@ -28,3 +49,23 @@ rerankHybrid(
|
||||
#### Returns
|
||||
|
||||
`Promise`<`RecordBatch`<`any`>>
|
||||
|
||||
***
|
||||
|
||||
### rerankVector()?
|
||||
|
||||
```ts
|
||||
optional rerankVector(query, results): Promise<RecordBatch<any>>
|
||||
```
|
||||
|
||||
Rerank one vector result list. The query string is empty for vector queries.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **query**: `string`
|
||||
|
||||
* **results**: `RecordBatch`<`any`>
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`RecordBatch`<`any`>>
|
||||
|
||||
@@ -106,6 +106,15 @@ model-based reranker from TypeScript or Rust, you must implement the hybrid rera
|
||||
yourself.
|
||||
</Note>
|
||||
|
||||
{/*
|
||||
Draft for the single-mode reranking SDK release. Replace the hybrid-only SDK
|
||||
guidance in the note above with this paragraph.
|
||||
|
||||
Rust supports vector, full-text and hybrid reranking. TypeScript supports vector
|
||||
and hybrid reranking. Both SDKs provide `RRFReranker` and let you implement a
|
||||
[custom reranker](#custom).
|
||||
*/}
|
||||
|
||||
|
||||
### Multi-vector reranking {#multi-vector-reranking}
|
||||
Use `rerank_multivector()` to combine result sets from several vector queries.
|
||||
@@ -142,6 +151,14 @@ Python custom rerankers implement `rerank_hybrid()` and can optionally implement
|
||||
`rerank_vector()` and `rerank_fts()`. TypeScript and Rust expose hybrid reranking
|
||||
interfaces. See [the interface requirements](#custom) before implementing one.
|
||||
|
||||
{/*
|
||||
Draft for the single-mode reranking SDK release. Replace the TypeScript and
|
||||
Rust sentence above with this sentence.
|
||||
|
||||
For single-mode searches, Rust exposes vector and full-text callbacks and
|
||||
TypeScript exposes a vector callback.
|
||||
*/}
|
||||
|
||||
## Algorithm options
|
||||
|
||||
The following sections describe the Python constructor options and examples.
|
||||
@@ -168,6 +185,26 @@ why it's the default reranker for LanceDB hybrid search. The implementation foll
|
||||
> Because RRF fuses two or more ranked lists, it can't rerank a single vector or full-text result set
|
||||
> on its own. Calling `rerank_vector` or `rerank_fts` on an `RRFReranker` raises `NotImplementedError`.
|
||||
|
||||
{/*
|
||||
Draft for the single-mode reranking SDK release. Replace the supported query
|
||||
types note above with these paragraphs.
|
||||
|
||||
Use `RRFReranker` with vector-only, full-text-only or hybrid search in Python
|
||||
and Rust, or with vector-only or hybrid search in TypeScript. Python also
|
||||
supports [multi-vector reranking](/reranking#multi-vector-reranking).
|
||||
|
||||
On a single ranked list, `RRFReranker` keeps retrieval order and computes
|
||||
`_relevance_score` as `1 / (rank + K)`, starting at rank 1. It scores by position
|
||||
without requiring `_rowid` and includes the score column on empty results. In
|
||||
Python, `return_score="all"` also keeps `_distance` for vector search or
|
||||
`_score` for full-text search. When passing a precomputed vector to the Python
|
||||
query builder, supply the text with `.rerank(reranker, query_string=query)`.
|
||||
|
||||
For independent searches against a single-vector column, submit one query
|
||||
vector per search. A multivector column combines multiple query vectors into
|
||||
one ranked list.
|
||||
*/}
|
||||
|
||||
|
||||
<CodeGroup>
|
||||
<CodeBlock filename="Python" language="Python" icon="python">
|
||||
@@ -363,6 +400,27 @@ The Python base class exposes hybrid, vector-only, and FTS-only rerank hooks. Ty
|
||||
currently expose the custom reranker interface for hybrid reranking. In Rust, a custom reranker must
|
||||
also satisfy the trait bounds `Debug + Send + Sync`.
|
||||
|
||||
{/*
|
||||
Draft for the single-mode reranking SDK release. Keep the Python sentence and
|
||||
replace the TypeScript and Rust guidance above with this section.
|
||||
|
||||
- In Rust, implement `Reranker` with `rerank_hybrid()` and override
|
||||
`rerank_vector()` or `rerank_fts()` for the single-mode queries you support.
|
||||
Pass the reranker to `.rerank(...)` on a vector or full-text query. The vector
|
||||
callback receives an empty query string and the full-text callback receives
|
||||
the search text. The trait requires `Debug + Send + Sync`.
|
||||
- In TypeScript, implement `rerankHybrid()` and add `rerankVector()` to use the
|
||||
reranker with `table.vectorSearch(...).rerank(...)`. The vector callback
|
||||
receives an empty query string.
|
||||
|
||||
Hybrid search calls the hybrid callback once with both lists. In Rust and
|
||||
TypeScript, single-mode callbacks receive Arrow record batches and return a
|
||||
batch in relevance order. By default the output schema keeps the
|
||||
input fields and adds a non-nullable Float32 `_relevance_score`. If your callback
|
||||
changes the output fields, declare its schema with `output_schema()` in Rust or
|
||||
`outputSchema()` in TypeScript.
|
||||
*/}
|
||||
|
||||
### Interface {#custom-interface}
|
||||
|
||||
The `Reranker` base interface comes with a `merge_results()` method that can be used to combine the
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import * as path from "node:path";
|
||||
import { RecordBatch } from "apache-arrow";
|
||||
import { Field, Float64, RecordBatch, Schema } from "apache-arrow";
|
||||
import * as tmp from "tmp";
|
||||
import { Connection, Index, Table, connect, makeArrowTable } from "../lancedb";
|
||||
import { RRFReranker } from "../lancedb/rerankers";
|
||||
@@ -108,6 +108,122 @@ describe("rerankers", function () {
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("returns one-based RRF scores and the declared vector query schema", async function () {
|
||||
const query = table
|
||||
.vectorSearch([0.1, 0.1])
|
||||
.limit(2)
|
||||
.select(["text"])
|
||||
.rerank(await RRFReranker.create());
|
||||
const schema = await query.outputSchema();
|
||||
const result = await query.toArrow();
|
||||
|
||||
expect(result.schema.fields).toEqual(schema.fields);
|
||||
expect(schema.fields.map((field) => field.name)).toEqual([
|
||||
"text",
|
||||
"_distance",
|
||||
"_relevance_score",
|
||||
]);
|
||||
expect(result.getChild("text")?.toArray()).toEqual(["dog", "cat"]);
|
||||
const scores = result.getChild("_relevance_score")?.toArray();
|
||||
expect(scores?.[0]).toBeCloseTo(1 / 61, 8);
|
||||
expect(scores?.[1]).toBeCloseTo(1 / 62, 8);
|
||||
});
|
||||
|
||||
it("preserves the reranked schema for an empty vector result", async function () {
|
||||
const query = table
|
||||
.vectorSearch([0.1, 0.1])
|
||||
.where("text = 'absent'")
|
||||
.withRowId()
|
||||
.rerank(await RRFReranker.create());
|
||||
const schema = await query.outputSchema();
|
||||
const result = await query.toArrow();
|
||||
|
||||
expect(result.numRows).toBe(0);
|
||||
expect(result.schema.fields).toEqual(schema.fields);
|
||||
expect(result.schema.fields.map((field) => field.name)).toEqual(
|
||||
expect.arrayContaining(["_rowid", "_relevance_score"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("dispatches to a custom vector callback with its declared output fields", async function () {
|
||||
const rerankedScore = 0.75;
|
||||
const declared = new Schema([
|
||||
new Field("_relevance_score", new Float64(), false),
|
||||
]);
|
||||
const rerankVector = jest.fn(
|
||||
async (_query: string, results: RecordBatch) => {
|
||||
expect(results.numRows).toBe(2);
|
||||
return makeArrowTable(
|
||||
// biome-ignore lint/style/useNamingConvention: this is the lance field name
|
||||
[{ _relevance_score: rerankedScore }],
|
||||
{ schema: declared },
|
||||
).batches[0];
|
||||
},
|
||||
);
|
||||
const rerankHybrid = jest.fn(async () => {
|
||||
throw new Error("unexpected hybrid callback");
|
||||
});
|
||||
const query = table
|
||||
.vectorSearch([0.1, 0.1])
|
||||
.limit(2)
|
||||
.rerank({
|
||||
rerankVector,
|
||||
rerankHybrid,
|
||||
outputSchema: () => declared,
|
||||
});
|
||||
expect((await query.outputSchema()).fields).toEqual(declared.fields);
|
||||
expect(rerankVector).not.toHaveBeenCalled();
|
||||
const result = await query.toArrow();
|
||||
expect(result.getChild("_relevance_score")?.toArray()).toEqual(
|
||||
new Float64Array([rerankedScore]),
|
||||
);
|
||||
expect(rerankVector).toHaveBeenCalledTimes(1);
|
||||
expect(rerankHybrid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a rejected rerankVector callback to the query caller", async function () {
|
||||
const rerankVector = jest.fn(async () => {
|
||||
throw new Error("vector scoring failed");
|
||||
});
|
||||
const rerankHybrid = jest.fn(async () => {
|
||||
throw new Error("unexpected hybrid callback");
|
||||
});
|
||||
const query = table
|
||||
.vectorSearch([0.1, 0.1])
|
||||
.rerank({ rerankVector, rerankHybrid });
|
||||
|
||||
await expect(query.toArrow()).rejects.toThrow("vector scoring failed");
|
||||
expect(rerankVector).toHaveBeenCalledTimes(1);
|
||||
expect(rerankHybrid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("applies the query timeout while rerankVector is pending", async function () {
|
||||
let rejectPending: ((error: Error) => void) | undefined;
|
||||
const rerankVector = jest.fn(
|
||||
() =>
|
||||
new Promise<RecordBatch>((_resolve, reject) => {
|
||||
rejectPending = reject;
|
||||
}),
|
||||
);
|
||||
const rerankHybrid = jest.fn(async () => {
|
||||
throw new Error("unexpected hybrid callback");
|
||||
});
|
||||
const query = table
|
||||
.vectorSearch([0.1, 0.1])
|
||||
.rerank({ rerankVector, rerankHybrid });
|
||||
|
||||
try {
|
||||
await expect(query.toArrow({ timeoutMs: 500 })).rejects.toThrow(
|
||||
"Query timeout after 500 ms",
|
||||
);
|
||||
expect(rerankVector).toHaveBeenCalledTimes(1);
|
||||
expect(rerankHybrid).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
rejectPending?.(new Error("callback rejected after query timeout"));
|
||||
}
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
});
|
||||
|
||||
it("does not keep process alive after rerank query", async function () {
|
||||
const script = `
|
||||
import * as lancedb from "./dist/index.js";
|
||||
|
||||
+39
-15
@@ -1,7 +1,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import type { Data as ArrowData } from "apache-arrow";
|
||||
import { type Data as ArrowData, tableToIPC } from "apache-arrow";
|
||||
import {
|
||||
Table as ArrowTable,
|
||||
DataType,
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
RecordBatch,
|
||||
Schema,
|
||||
Struct,
|
||||
createEmptyTable,
|
||||
extractVectorBuffer,
|
||||
fromBufferToRecordBatch,
|
||||
fromRecordBatchToBuffer,
|
||||
@@ -1211,21 +1212,44 @@ export class VectorQuery extends StandardQueryBase<NativeVectorQuery> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply a reranker to this vector or hybrid query. */
|
||||
rerank(reranker: Reranker): VectorQuery {
|
||||
this.doVectorCall((inner) =>
|
||||
inner.rerank(async (args) => {
|
||||
const vecResults = await fromBufferToRecordBatch(args.vecResults);
|
||||
const ftsResults = await fromBufferToRecordBatch(args.ftsResults);
|
||||
const result = await reranker.rerankHybrid(
|
||||
args.query,
|
||||
vecResults as RecordBatch,
|
||||
ftsResults as RecordBatch,
|
||||
);
|
||||
|
||||
const buffer = fromRecordBatchToBuffer(result);
|
||||
return buffer;
|
||||
}),
|
||||
);
|
||||
this.doVectorCall((inner) => {
|
||||
const rerankVector = reranker.rerankVector?.bind(reranker);
|
||||
const outputSchema = reranker.outputSchema?.bind(reranker);
|
||||
inner.rerank(
|
||||
async (args) => {
|
||||
const vecResults = await fromBufferToRecordBatch(args.vecResults);
|
||||
const ftsResults = await fromBufferToRecordBatch(args.ftsResults);
|
||||
const result = await reranker.rerankHybrid(
|
||||
args.query,
|
||||
vecResults as RecordBatch,
|
||||
ftsResults as RecordBatch,
|
||||
);
|
||||
return fromRecordBatchToBuffer(result);
|
||||
},
|
||||
rerankVector
|
||||
? async (args) => {
|
||||
const results = await fromBufferToRecordBatch(args.vecResults);
|
||||
if (results === null) {
|
||||
throw new Error(
|
||||
"Expected an Arrow record batch of vector results",
|
||||
);
|
||||
}
|
||||
return fromRecordBatchToBuffer(
|
||||
await rerankVector(args.query, results),
|
||||
);
|
||||
}
|
||||
: undefined,
|
||||
outputSchema
|
||||
? async (buffer) => {
|
||||
const inputSchema = tableFromIPC(buffer).schema;
|
||||
const result = await outputSchema(inputSchema);
|
||||
return Buffer.from(tableToIPC(createEmptyTable(result), "file"));
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
});
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { RecordBatch } from "apache-arrow";
|
||||
import { RecordBatch, Schema } from "apache-arrow";
|
||||
|
||||
export * from "./rrf";
|
||||
|
||||
// Interface for a reranker. A reranker is used to rerank the results from a
|
||||
// vector and FTS search. This is useful for combining the results from both
|
||||
// search methods.
|
||||
/** Reranks vector or hybrid search results. */
|
||||
export interface Reranker {
|
||||
rerankHybrid(
|
||||
query: string,
|
||||
vecResults: RecordBatch,
|
||||
ftsResults: RecordBatch,
|
||||
): Promise<RecordBatch>;
|
||||
|
||||
/** Rerank one vector result list. The query string is empty for vector queries. */
|
||||
rerankVector?(query: string, results: RecordBatch): Promise<RecordBatch>;
|
||||
|
||||
/**
|
||||
* Declare the output fields for vector reranking. The default keeps the
|
||||
* input fields and appends a non-nullable Float32 `_relevance_score` field.
|
||||
*/
|
||||
outputSchema?(input: Schema): Schema | Promise<Schema>;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,22 @@ export class RRFReranker {
|
||||
);
|
||||
}
|
||||
|
||||
/** Score vector search results by their one-based rank. */
|
||||
async rerankVector(
|
||||
query: string,
|
||||
results: RecordBatch,
|
||||
): Promise<RecordBatch> {
|
||||
const buffer = await this.inner.rerankVector(
|
||||
query,
|
||||
await fromRecordBatchToBuffer(results),
|
||||
);
|
||||
const recordBatch = await fromBufferToRecordBatch(buffer);
|
||||
if (recordBatch === null) {
|
||||
throw new Error("Expected an Arrow record batch from the RRF reranker");
|
||||
}
|
||||
return recordBatch;
|
||||
}
|
||||
|
||||
async rerankHybrid(
|
||||
query: string,
|
||||
vecResults: RecordBatch,
|
||||
|
||||
+4
-3
@@ -6,8 +6,7 @@ use std::sync::Arc;
|
||||
use crate::error::NapiErrorExt;
|
||||
use crate::error::convert_error;
|
||||
use crate::iterator::RecordBatchIterator;
|
||||
use crate::rerankers::RerankHybridCallbackArgs;
|
||||
use crate::rerankers::Reranker;
|
||||
use crate::rerankers::{RerankHybridCallbackArgs, RerankVectorCallbackArgs, Reranker};
|
||||
use crate::util::{parse_distance_type, schema_to_buffer};
|
||||
use arrow_array::{
|
||||
Array, Float16Array as ArrowFloat16Array, Float32Array as ArrowFloat32Array,
|
||||
@@ -404,8 +403,10 @@ impl VectorQuery {
|
||||
pub fn rerank(
|
||||
&mut self,
|
||||
rerank_hybrid: Function<RerankHybridCallbackArgs, Promise<Buffer>>,
|
||||
rerank_vector: Option<Function<RerankVectorCallbackArgs, Promise<Buffer>>>,
|
||||
output_schema: Option<Function<Buffer, Promise<Buffer>>>,
|
||||
) -> napi::Result<()> {
|
||||
let reranker = Reranker::new(rerank_hybrid)?;
|
||||
let reranker = Reranker::new(rerank_hybrid, rerank_vector, output_schema)?;
|
||||
self.inner = self.inner.clone().rerank(Arc::new(reranker));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+98
-50
@@ -2,74 +2,98 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use arrow_array::RecordBatch;
|
||||
use arrow_schema::SchemaRef;
|
||||
use async_trait::async_trait;
|
||||
use napi::{bindgen_prelude::*, threadsafe_function::ThreadsafeFunction};
|
||||
use napi_derive::napi;
|
||||
|
||||
use lancedb::ipc::batches_to_ipc_file;
|
||||
use lancedb::Error;
|
||||
use lancedb::ipc::{
|
||||
batches_to_ipc_file, ipc_file_to_batches, ipc_file_to_schema, schema_to_ipc_file,
|
||||
};
|
||||
use lancedb::rerankers::Reranker as LanceDBReranker;
|
||||
use lancedb::{error::Error, ipc::ipc_file_to_batches};
|
||||
|
||||
use crate::error::NapiErrorExt;
|
||||
|
||||
type RerankHybridFn = ThreadsafeFunction<
|
||||
RerankHybridCallbackArgs,
|
||||
Promise<Buffer>,
|
||||
RerankHybridCallbackArgs,
|
||||
Status,
|
||||
false,
|
||||
true,
|
||||
>;
|
||||
type RerankFn<Args> = ThreadsafeFunction<Args, Promise<Buffer>, Args, Status, false, true>;
|
||||
|
||||
/// Reranker implementation that "wraps" a NodeJS Reranker implementation.
|
||||
/// This contains references to the callbacks that can be used to invoke the
|
||||
/// reranking methods on the NodeJS implementation and handles serializing the
|
||||
/// record batches to Arrow IPC buffers.
|
||||
pub struct Reranker {
|
||||
rerank_hybrid: RerankHybridFn,
|
||||
rerank_hybrid: RerankFn<RerankHybridCallbackArgs>,
|
||||
rerank_vector: Option<RerankFn<RerankVectorCallbackArgs>>,
|
||||
output_schema: Option<RerankFn<Buffer>>,
|
||||
}
|
||||
|
||||
impl Reranker {
|
||||
pub fn new(
|
||||
rerank_hybrid: Function<RerankHybridCallbackArgs, Promise<Buffer>>,
|
||||
rerank_vector: Option<Function<RerankVectorCallbackArgs, Promise<Buffer>>>,
|
||||
output_schema: Option<Function<Buffer, Promise<Buffer>>>,
|
||||
) -> napi::Result<Self> {
|
||||
let rerank_hybrid = rerank_hybrid
|
||||
.build_threadsafe_function()
|
||||
.weak::<true>()
|
||||
.build()?;
|
||||
Ok(Self { rerank_hybrid })
|
||||
let rerank_vector = rerank_vector
|
||||
.map(|callback| callback.build_threadsafe_function().weak::<true>().build())
|
||||
.transpose()?;
|
||||
let output_schema = output_schema
|
||||
.map(|callback| callback.build_threadsafe_function().weak::<true>().build())
|
||||
.transpose()?;
|
||||
Ok(Self {
|
||||
rerank_hybrid,
|
||||
rerank_vector,
|
||||
output_schema,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl lancedb::rerankers::Reranker for Reranker {
|
||||
impl LanceDBReranker for Reranker {
|
||||
async fn output_schema(&self, input: &SchemaRef) -> lancedb::Result<Option<SchemaRef>> {
|
||||
let Some(callback) = &self.output_schema else {
|
||||
return Ok(None);
|
||||
};
|
||||
let input = Buffer::from(schema_to_ipc_file(input.as_ref())?);
|
||||
let output = callback_buffer(callback.call_async(input).await).await?;
|
||||
Ok(Some(ipc_file_to_schema(output.to_vec())?))
|
||||
}
|
||||
|
||||
async fn rerank_vector(
|
||||
&self,
|
||||
query: &str,
|
||||
vec_results: RecordBatch,
|
||||
) -> lancedb::Result<RecordBatch> {
|
||||
let callback = self
|
||||
.rerank_vector
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::NotSupported {
|
||||
message: "the reranker does not implement rerankVector".into(),
|
||||
})?;
|
||||
let args = RerankVectorCallbackArgs {
|
||||
query: query.to_string(),
|
||||
vec_results: record_batch_to_buffer(vec_results)?,
|
||||
};
|
||||
let buffer = callback_buffer(callback.call_async(args).await).await?;
|
||||
buffer_to_record_batch(buffer)
|
||||
}
|
||||
|
||||
async fn rerank_hybrid(
|
||||
&self,
|
||||
query: &str,
|
||||
vector_results: RecordBatch,
|
||||
fts_results: RecordBatch,
|
||||
) -> lancedb::error::Result<RecordBatch> {
|
||||
let callback_args = RerankHybridCallbackArgs {
|
||||
) -> lancedb::Result<RecordBatch> {
|
||||
let args = RerankHybridCallbackArgs {
|
||||
query: query.to_string(),
|
||||
vec_results: Buffer::from(batches_to_ipc_file(&[vector_results])?.as_ref()),
|
||||
fts_results: Buffer::from(batches_to_ipc_file(&[fts_results])?.as_ref()),
|
||||
vec_results: record_batch_to_buffer(vector_results)?,
|
||||
fts_results: record_batch_to_buffer(fts_results)?,
|
||||
};
|
||||
let promised_buffer: Promise<Buffer> = self
|
||||
.rerank_hybrid
|
||||
.call_async(callback_args)
|
||||
.await
|
||||
.map_err(|e| Error::Runtime {
|
||||
message: format!("napi error status={}, reason={}", e.status, e.reason),
|
||||
})?;
|
||||
let buffer = promised_buffer.await.map_err(|e| Error::Runtime {
|
||||
message: format!("napi error status={}, reason={}", e.status, e.reason),
|
||||
})?;
|
||||
let mut reader = ipc_file_to_batches(buffer.to_vec())?;
|
||||
let result = reader.next().ok_or(Error::Runtime {
|
||||
message: "reranker result deserialization failed".to_string(),
|
||||
})??;
|
||||
|
||||
return Ok(result);
|
||||
let buffer = callback_buffer(self.rerank_hybrid.call_async(args).await).await?;
|
||||
buffer_to_record_batch(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,16 +110,33 @@ pub struct RerankHybridCallbackArgs {
|
||||
pub fts_results: Buffer,
|
||||
}
|
||||
|
||||
fn buffer_to_record_batch(buffer: Buffer) -> Result<RecordBatch> {
|
||||
let mut reader = ipc_file_to_batches(buffer.to_vec()).default_error()?;
|
||||
reader
|
||||
#[napi(object)]
|
||||
pub struct RerankVectorCallbackArgs {
|
||||
pub query: String,
|
||||
pub vec_results: Buffer,
|
||||
}
|
||||
|
||||
async fn callback_buffer(result: napi::Result<Promise<Buffer>>) -> lancedb::Result<Buffer> {
|
||||
let to_error = |error: napi::Error| Error::Runtime {
|
||||
message: format!(
|
||||
"napi error status={}, reason={}",
|
||||
error.status, error.reason
|
||||
),
|
||||
};
|
||||
result.map_err(to_error)?.await.map_err(to_error)
|
||||
}
|
||||
|
||||
fn record_batch_to_buffer(batch: RecordBatch) -> lancedb::Result<Buffer> {
|
||||
Ok(Buffer::from(batches_to_ipc_file(&[batch])?))
|
||||
}
|
||||
|
||||
fn buffer_to_record_batch(buffer: Buffer) -> lancedb::Result<RecordBatch> {
|
||||
let mut reader = ipc_file_to_batches(buffer.to_vec())?;
|
||||
// Arrow JS can write a zero-row result as an IPC file with only its schema.
|
||||
Ok(reader
|
||||
.next()
|
||||
.ok_or(Error::InvalidInput {
|
||||
message: "expected buffer containing record batch".to_string(),
|
||||
})
|
||||
.default_error()?
|
||||
.map_err(Error::from)
|
||||
.default_error()
|
||||
.transpose()?
|
||||
.unwrap_or_else(|| RecordBatch::new_empty(reader.schema())))
|
||||
}
|
||||
|
||||
/// Wrapper around rust RRFReranker
|
||||
@@ -121,6 +162,17 @@ impl RRFReranker {
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn rerank_vector(&self, query: String, vec_results: Buffer) -> Result<Buffer> {
|
||||
let vec_results = buffer_to_record_batch(vec_results).default_error()?;
|
||||
let result = self
|
||||
.inner
|
||||
.rerank_vector(&query, vec_results)
|
||||
.await
|
||||
.default_error()?;
|
||||
record_batch_to_buffer(result).default_error()
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn rerank_hybrid(
|
||||
&self,
|
||||
@@ -128,17 +180,13 @@ impl RRFReranker {
|
||||
vec_results: Buffer,
|
||||
fts_results: Buffer,
|
||||
) -> Result<Buffer> {
|
||||
let vec_results = buffer_to_record_batch(vec_results)?;
|
||||
let fts_results = buffer_to_record_batch(fts_results)?;
|
||||
|
||||
let vec_results = buffer_to_record_batch(vec_results).default_error()?;
|
||||
let fts_results = buffer_to_record_batch(fts_results).default_error()?;
|
||||
let result = self
|
||||
.inner
|
||||
.rerank_hybrid(&query, vec_results, fts_results)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let result_buff = batches_to_ipc_file(&[result]).default_error()?;
|
||||
|
||||
Ok(Buffer::from(result_buff.as_ref()))
|
||||
.default_error()?;
|
||||
record_batch_to_buffer(result).default_error()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ from pydantic_core import PydanticUndefined
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from lancedb._lancedb import (
|
||||
_parse_field_path,
|
||||
_share_hybrid_subquery_filter,
|
||||
_uses_sql_subquery_filter,
|
||||
fts_query_to_json,
|
||||
@@ -47,7 +48,13 @@ from .rerankers.base import Reranker
|
||||
from .rerankers.rrf import RRFReranker
|
||||
from .rerankers.util import check_reranker_result
|
||||
from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field
|
||||
from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme
|
||||
from .util import (
|
||||
_validate_query_vector,
|
||||
add_note,
|
||||
flatten_columns,
|
||||
get_uri_scheme,
|
||||
inf_vector_column_query,
|
||||
)
|
||||
from . import _wal_hybrid # WAL-PK-FUSION: delete.
|
||||
from ._blob import (
|
||||
BLOB_MODE_TO_HANDLING,
|
||||
@@ -181,6 +188,32 @@ def _rows_to_models(model: type[T], rows: List[dict]) -> List[T]:
|
||||
AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"]
|
||||
_SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray)
|
||||
|
||||
|
||||
def _uses_single_list_rrf(reranker: Optional[Reranker]) -> bool:
|
||||
# A subclass can supply its own vector callback with batch semantics.
|
||||
return (
|
||||
isinstance(reranker, RRFReranker)
|
||||
and getattr(reranker.rerank_vector, "__func__", None)
|
||||
is RRFReranker.rerank_vector
|
||||
)
|
||||
|
||||
|
||||
def _check_rrf_multivector_column(
|
||||
schema: Optional[pa.Schema], column: Optional[str], dimension: int
|
||||
) -> None:
|
||||
if schema is not None:
|
||||
if column is None:
|
||||
column = inf_vector_column_query(schema, dim=dimension)
|
||||
column_type = schema
|
||||
for name in _parse_field_path(column):
|
||||
column_type = column_type.field(name).type
|
||||
if pa.types.is_list(column_type):
|
||||
return
|
||||
raise NotImplementedError(
|
||||
"RRF does not support batched vector searches. Run one query per vector."
|
||||
)
|
||||
|
||||
|
||||
# Number of rows a hybrid query returns when no limit was set on it. This
|
||||
# mirrors the default the Rust query builder applies to its sub-queries.
|
||||
DEFAULT_HYBRID_LIMIT = 10
|
||||
@@ -2779,6 +2812,24 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def _query_for_scan(
|
||||
self,
|
||||
blob_sources: Optional[dict[str, str]] = None,
|
||||
schema: Optional[pa.Schema] = None,
|
||||
) -> Query:
|
||||
query = super()._query_for_scan(blob_sources, schema)
|
||||
vectors = query.vector
|
||||
if (
|
||||
_uses_single_list_rrf(self._reranker)
|
||||
and vectors
|
||||
and len(vectors) > 1
|
||||
and isinstance(vectors[0], list)
|
||||
):
|
||||
if schema is None:
|
||||
schema = self._table.schema
|
||||
_check_rrf_multivector_column(schema, query.vector_column, len(vectors[0]))
|
||||
return query
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
"""
|
||||
Build a Query object
|
||||
@@ -5881,11 +5932,25 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table)
|
||||
)
|
||||
|
||||
def _rrf_multivector_input(self) -> Optional[tuple[Optional[str], int]]:
|
||||
if _uses_single_list_rrf(self._reranker):
|
||||
request = self._inner.to_query_request()
|
||||
vectors = request.query_vector
|
||||
if vectors and len(vectors) > 1:
|
||||
return request.column, len(vectors[0])
|
||||
return None
|
||||
|
||||
async def _check_rrf_vector_query(self) -> None:
|
||||
if (vector_input := self._rrf_multivector_input()) is not None:
|
||||
schema = await self._table.schema() if self._table is not None else None
|
||||
_check_rrf_multivector_column(schema, *vector_input)
|
||||
|
||||
async def _execute_eager(
|
||||
self,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
await self._check_rrf_vector_query()
|
||||
if self._force_local_namespace and self._table is not None:
|
||||
# Preserve local execution for the vector leg so it uses the same
|
||||
# embedded table snapshot as the FTS leg.
|
||||
@@ -5905,6 +5970,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
if (vector_input := self._rrf_multivector_input()) is not None:
|
||||
schema = self._table._schema_sync() if self._table is not None else None
|
||||
_check_rrf_multivector_column(schema, *vector_input)
|
||||
results = super()._execute_eager_sync(timeout=timeout)
|
||||
if self._reranker:
|
||||
source = results
|
||||
@@ -5919,6 +5987,7 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
timeout: Optional[timedelta] = None,
|
||||
blob_sources: Optional[dict[str, str]] = None,
|
||||
) -> AsyncRecordBatchReader:
|
||||
await self._check_rrf_vector_query()
|
||||
reader = await super()._execute_batches(
|
||||
max_batch_length=max_batch_length,
|
||||
timeout=timeout,
|
||||
|
||||
@@ -14,20 +14,38 @@ if TYPE_CHECKING:
|
||||
|
||||
class RRFReranker(Reranker):
|
||||
"""
|
||||
Reranks the results using Reciprocal Rank Fusion(RRF) algorithm based
|
||||
on the scores of vector and FTS search.
|
||||
Rerank vector, full-text, or hybrid search results using Reciprocal Rank
|
||||
Fusion (RRF). Each list contributes `1 / (K + rank)` per row, with ranks
|
||||
starting at 1. A single list keeps its input order.
|
||||
|
||||
For vector reranking, run independent searches one query vector at a time.
|
||||
Multiple query vectors against a multivector column form one ranked list.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
K : int, default 60
|
||||
A constant used in the RRF formula (default is 60). Experiments
|
||||
indicate that k = 60 was near-optimal, but that the choice is
|
||||
not critical. See paper:
|
||||
https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
|
||||
The constant used in RRF formula. Research suggests K=60 is
|
||||
near-optimal, but the choice is not critical.
|
||||
return_score : str, default "relevance"
|
||||
opntions are "relevance" or "all"
|
||||
The type of score to return. If "relevance", will return only the relevance
|
||||
score. If "all", will return all scores from the vector and FTS search along
|
||||
with the relevance score.
|
||||
Whether to return only "_relevance_score" or "all" scores
|
||||
including "_distance" and "_score".
|
||||
|
||||
Examples
|
||||
--------
|
||||
For a vector query, pass the query text to the builder when supplying a
|
||||
precomputed vector. Full-text and hybrid queries already have query text.
|
||||
|
||||
```python
|
||||
reranker = RRFReranker(K=60)
|
||||
vector = table.search(query_vector).rerank(reranker, query_string=query).to_arrow()
|
||||
fts = table.search(query, query_type="fts").rerank(reranker).to_arrow()
|
||||
```
|
||||
|
||||
References
|
||||
----------
|
||||
Cormack et al. (2009). "Reciprocal rank fusion outperforms condorcet
|
||||
and individual rank learning methods." SIGIR '09.
|
||||
https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
|
||||
"""
|
||||
|
||||
def __init__(self, K: int = 60, return_score="relevance"):
|
||||
@@ -39,6 +57,23 @@ class RRFReranker(Reranker):
|
||||
def __str__(self):
|
||||
return f"RRFReranker(K={self.K})"
|
||||
|
||||
def _rerank_list(self, results: pa.Table) -> pa.Table:
|
||||
scores = pa.array(
|
||||
[1 / (rank + self.K) for rank in range(1, len(results) + 1)],
|
||||
type=pa.float32(),
|
||||
)
|
||||
return self._keep_relevance_score(
|
||||
results.append_column("_relevance_score", scores)
|
||||
)
|
||||
|
||||
def rerank_vector(self, query: str, vector_results: pa.Table) -> pa.Table:
|
||||
"""Score vector search results in rank order."""
|
||||
return self._rerank_list(vector_results)
|
||||
|
||||
def rerank_fts(self, query: str, fts_results: pa.Table) -> pa.Table:
|
||||
"""Score full-text search results in rank order."""
|
||||
return self._rerank_list(fts_results)
|
||||
|
||||
def rerank_hybrid(
|
||||
self,
|
||||
query: str, # noqa: F821
|
||||
@@ -81,10 +116,7 @@ class RRFReranker(Reranker):
|
||||
deduplicate: bool = True,
|
||||
):
|
||||
"""
|
||||
Overridden method to rerank the results from multiple vector searches.
|
||||
This leverages the RRF hybrid reranking algorithm to combine the
|
||||
results from multiple vector searches as it doesn't support reranking
|
||||
vector results individually.
|
||||
Combine the ranked lists from multiple vector searches using RRF.
|
||||
|
||||
Set `deduplicate=False` to keep all result rows with their fused scores.
|
||||
"""
|
||||
|
||||
@@ -13,6 +13,7 @@ import pyarrow.compute as pc
|
||||
import pytest
|
||||
from lancedb.conftest import MockTextEmbeddingFunction # noqa
|
||||
from lancedb.embeddings import EmbeddingFunctionRegistry
|
||||
from lancedb.index import FTS
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
from lancedb.rerankers import (
|
||||
LinearCombinationReranker,
|
||||
@@ -440,6 +441,153 @@ def test_mrr_multivector_rewards_consensus():
|
||||
assert result["_rowid"].to_pylist()[0] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
@pytest.mark.parametrize("query_type", ["vector", "fts"])
|
||||
@pytest.mark.parametrize(
|
||||
"return_score,with_row_id,empty",
|
||||
[
|
||||
("relevance", False, False),
|
||||
("all", False, False),
|
||||
("relevance", True, True),
|
||||
("all", True, True),
|
||||
],
|
||||
)
|
||||
async def test_rrf_single_mode_query(
|
||||
tmp_path, asynchronous, query_type, return_score, with_row_id, empty
|
||||
):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"docs",
|
||||
[
|
||||
{"id": 1, "text": "dog dog", "vector": [0.0, 0.0]},
|
||||
{"id": 2, "text": "cat", "vector": [1.0, 1.0]},
|
||||
{"id": 3, "text": "dog in a garden", "vector": [2.0, 2.0]},
|
||||
],
|
||||
)
|
||||
table.create_index("text", config=FTS())
|
||||
term = "absent" if empty else "dog"
|
||||
reranker = RRFReranker(return_score=return_score)
|
||||
|
||||
if asynchronous:
|
||||
async_db = await lancedb.connect_async(tmp_path)
|
||||
async_table = await async_db.open_table("docs")
|
||||
if query_type == "vector":
|
||||
query = async_table.query().nearest_to([0.0, 0.0])
|
||||
else:
|
||||
query = async_table.query().nearest_to_text(term)
|
||||
elif query_type == "vector":
|
||||
query = table.search([0.0, 0.0])
|
||||
else:
|
||||
query = table.search(term, query_type="fts")
|
||||
|
||||
query = query.select(["id"]).limit(2)
|
||||
if with_row_id:
|
||||
query = query.with_row_id() if asynchronous else query.with_row_id(True)
|
||||
if empty and query_type == "vector":
|
||||
query = query.where("id < 0")
|
||||
if query_type == "vector":
|
||||
query = query.rerank(reranker, query_string="dog")
|
||||
else:
|
||||
query = query.rerank(reranker)
|
||||
result = await query.to_arrow() if asynchronous else query.to_arrow()
|
||||
|
||||
expected_ids = [] if empty else [1, 2 if query_type == "vector" else 3]
|
||||
assert result["id"].to_pylist() == expected_ids
|
||||
assert result.column_names.count("_relevance_score") == 1
|
||||
assert result["_relevance_score"].type == pa.float32()
|
||||
assert result["_relevance_score"].to_pylist() == pytest.approx(
|
||||
[1 / (61 + index) for index in range(len(expected_ids))]
|
||||
)
|
||||
source_score = "_distance" if query_type == "vector" else "_score"
|
||||
assert (source_score in result.column_names) == (return_score == "all")
|
||||
# The synchronous builder also requests row IDs for return_score="all".
|
||||
assert ("_rowid" in result.column_names) == (
|
||||
with_row_id or (not asynchronous and return_score == "all")
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
async def test_rrf_rejects_independent_vector_batches(tmp_path, asynchronous):
|
||||
rows = [
|
||||
{"id": index, "vector": [x, 0.0]}
|
||||
for index, x in enumerate([0.0, 1.0, 3.0, 4.0])
|
||||
]
|
||||
vectors = [[0.0, 0.0], [4.0, 0.0]]
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("docs", rows)
|
||||
query = table.query().nearest_to(vectors)
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", rows)
|
||||
query = table.search(vectors)
|
||||
|
||||
query = query.select(["id"]).limit(2)
|
||||
raw = await query.to_arrow() if asynchronous else query.to_arrow()
|
||||
assert sorted(zip(raw["query_index"].to_pylist(), raw["id"].to_pylist())) == [
|
||||
(0, 0),
|
||||
(0, 1),
|
||||
(1, 2),
|
||||
(1, 3),
|
||||
]
|
||||
|
||||
reranked = query.rerank(RRFReranker(), query_string="dog")
|
||||
with pytest.raises(NotImplementedError, match="RRF does not support batched"):
|
||||
if asynchronous:
|
||||
await reranked.to_arrow()
|
||||
else:
|
||||
reranked.to_arrow()
|
||||
with pytest.raises(NotImplementedError, match="RRF does not support batched"):
|
||||
if asynchronous:
|
||||
await reranked.to_batches()
|
||||
else:
|
||||
reranked.to_batches()
|
||||
|
||||
class CustomReranker(RRFReranker):
|
||||
def rerank_vector(self, query, results):
|
||||
return results.append_column(
|
||||
"_relevance_score", pa.array([1.0] * len(results), type=pa.float32())
|
||||
)
|
||||
|
||||
custom = query.rerank(CustomReranker(), query_string="dog")
|
||||
result = await custom.to_arrow() if asynchronous else custom.to_arrow()
|
||||
assert result["_relevance_score"].to_pylist() == [1.0] * 4
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
async def test_rrf_multivector_projected_query_index(tmp_path, asynchronous):
|
||||
tokens = pa.FixedSizeListArray.from_arrays(
|
||||
pa.array([1.0, 0.0, 0.0, 1.0], type=pa.float32()), 2
|
||||
)
|
||||
data = pa.table(
|
||||
{
|
||||
"vector": pa.ListArray.from_arrays([0, 2], tokens),
|
||||
"query_index": ["user data"],
|
||||
}
|
||||
)
|
||||
vectors = [[1.0, 0.0], [0.0, 1.0]]
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("docs", data)
|
||||
query = table.query().nearest_to(vectors).column("vector")
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", data)
|
||||
query = table.search(vectors, vector_column_name="vector")
|
||||
|
||||
query = (
|
||||
query.distance_type("cosine")
|
||||
.select(["query_index"])
|
||||
.rerank(RRFReranker(), query_string="dog")
|
||||
)
|
||||
result = await query.to_arrow() if asynchronous else query.to_arrow()
|
||||
assert result["query_index"].to_pylist() == ["user data"]
|
||||
assert result["_relevance_score"].to_pylist() == pytest.approx([1 / 61])
|
||||
|
||||
|
||||
def test_rrf_multivector_ranks_each_result_list():
|
||||
# RRF scores a document by its rank *within each* result list. The top hit
|
||||
# of the second list must score the same as the top hit of the first list,
|
||||
|
||||
+224
-11
@@ -34,7 +34,8 @@ use half::f16;
|
||||
/// Re-export Lance ColumnOrdering type for use in query ordering
|
||||
pub use lance::dataset::scanner::ColumnOrdering;
|
||||
use lance::dataset::{ROW_ID, scanner::DatasetRecordBatchStream};
|
||||
use lance_arrow::RecordBatchExt;
|
||||
use lance::index::vector::utils::get_vector_type;
|
||||
use lance_arrow::{RecordBatchExt, SchemaExt};
|
||||
use lance_datafusion::exec::{execute_plan, format_plan as format_analyzed_plan};
|
||||
use lance_index::scalar::FullTextSearchQuery;
|
||||
use lance_index::scalar::inverted::SCORE_COL;
|
||||
@@ -43,9 +44,11 @@ use lance_index::vector::DIST_COL;
|
||||
use crate::database::Database;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::rerankers::rrf::RRFReranker;
|
||||
use crate::rerankers::{NormalizeMethod, Reranker, check_reranker_result};
|
||||
use crate::rerankers::{
|
||||
NormalizeMethod, RELEVANCE_SCORE, Reranker, check_reranker_result, relevance_score_field,
|
||||
};
|
||||
use crate::table::{BaseTable, NativeTableExt};
|
||||
use crate::utils::{MaxBatchLengthStream, TimeoutStream};
|
||||
use crate::utils::{MaxBatchLengthStream, TimeoutStream, default_vector_column};
|
||||
use crate::{ApproxMode, DistanceType};
|
||||
use crate::{
|
||||
arrow::{SendableRecordBatchStream, SimpleRecordBatchStream},
|
||||
@@ -540,7 +543,26 @@ pub trait QueryBase {
|
||||
|
||||
/// Rerank the results using the specified reranker.
|
||||
///
|
||||
/// This is currently only supported for Hybrid Search.
|
||||
/// Vector, full-text, and hybrid queries each invoke their corresponding
|
||||
/// [`Reranker`] method. A vector query must produce one ranked list.
|
||||
/// Independent vector queries batched into one request are unsupported.
|
||||
/// Reranking a single list uses the requested projection, including row IDs
|
||||
/// when selected. Use [`ExecutableQuery::execute`] to collect candidates
|
||||
/// and apply the reranker.
|
||||
///
|
||||
/// ```
|
||||
/// use std::sync::Arc;
|
||||
/// use lancedb::{Table, Result, query::{ExecutableQuery, QueryBase}};
|
||||
/// use lancedb::rerankers::rrf::RRFReranker;
|
||||
///
|
||||
/// async fn search(table: &Table) -> Result<()> {
|
||||
/// let _results = table.vector_search(&[1.0_f32, 2.0])?
|
||||
/// .limit(10)
|
||||
/// .rerank(Arc::new(RRFReranker::default()))
|
||||
/// .execute().await?;
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
fn rerank(self, reranker: Arc<dyn Reranker>) -> Self;
|
||||
|
||||
/// The method to normalize the scores. Can be "rank" or "Score". If "Rank",
|
||||
@@ -1200,6 +1222,35 @@ impl Query {
|
||||
pub fn current_request(&self) -> &QueryRequest {
|
||||
&self.request
|
||||
}
|
||||
|
||||
fn single_search_rerank(&self) -> Option<SingleSearchRerank<'_>> {
|
||||
Some(SingleSearchRerank {
|
||||
reranker: self.request.reranker.as_deref()?,
|
||||
search: SingleSearch::FullText(self.request.full_text_search.as_ref()?),
|
||||
limit: self.request.limit,
|
||||
})
|
||||
}
|
||||
|
||||
fn candidate_request(&self) -> AnyQuery {
|
||||
let mut request = self.request.clone();
|
||||
if request.full_text_search.is_some() {
|
||||
// The SDK applies the reranker after reading the candidates,
|
||||
// including when the namespace service runs the search.
|
||||
request.reranker = None;
|
||||
}
|
||||
AnyQuery::Query(request)
|
||||
}
|
||||
|
||||
async fn inner_execute_with_options(
|
||||
&self,
|
||||
options: QueryExecutionOptions,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
Ok(self
|
||||
.parent
|
||||
.query(&self.candidate_request(), options)
|
||||
.await?
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl HasQuery for Query {
|
||||
@@ -1210,18 +1261,32 @@ impl HasQuery for Query {
|
||||
|
||||
impl ExecutableQuery for Query {
|
||||
async fn create_plan(&self, options: QueryExecutionOptions) -> Result<Arc<dyn ExecutionPlan>> {
|
||||
let req = AnyQuery::Query(self.request.clone());
|
||||
self.parent.clone().create_plan(&req, options).await
|
||||
self.parent
|
||||
.create_plan(&self.candidate_request(), options)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn execute_with_options(
|
||||
&self,
|
||||
options: QueryExecutionOptions,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
let query = AnyQuery::Query(self.request.clone());
|
||||
Ok(SendableRecordBatchStream::from(
|
||||
self.parent.clone().query(&query, options).await?,
|
||||
))
|
||||
if let Some(rerank) = self.single_search_rerank() {
|
||||
let candidates =
|
||||
self.inner_execute_with_options(options.without_output_batch_length_limit());
|
||||
return rerank.execute(candidates, options).await;
|
||||
}
|
||||
self.inner_execute_with_options(options).await
|
||||
}
|
||||
|
||||
async fn output_schema(&self) -> Result<SchemaRef> {
|
||||
let input = self
|
||||
.create_plan(QueryExecutionOptions::default())
|
||||
.await?
|
||||
.schema();
|
||||
match self.single_search_rerank() {
|
||||
Some(rerank) => rerank.output_schema(&input).await,
|
||||
None => Ok(input),
|
||||
}
|
||||
}
|
||||
|
||||
async fn explain_plan(&self, verbose: bool) -> Result<String> {
|
||||
@@ -1303,6 +1368,32 @@ impl Default for VectorQueryRequest {
|
||||
}
|
||||
|
||||
impl VectorQueryRequest {
|
||||
pub(crate) fn resolve_vector_column(
|
||||
&self,
|
||||
schema: &lance_core::datatypes::Schema,
|
||||
dimension: usize,
|
||||
) -> Result<(String, DataType, DataType)> {
|
||||
let column = match &self.column {
|
||||
Some(column) => column.clone(),
|
||||
None => {
|
||||
default_vector_column(&arrow_schema::Schema::from(schema), Some(dimension as i32))?
|
||||
}
|
||||
};
|
||||
let (vector_type, element_type) = get_vector_type(schema, &column)?;
|
||||
Ok((column, vector_type, element_type))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_rerank_batch(&self, is_batch: bool) -> Result<()> {
|
||||
if is_batch && self.base.reranker.is_some() && self.base.full_text_search.is_none() {
|
||||
return Err(Error::NotSupported {
|
||||
message:
|
||||
"reranking batched vector searches is unsupported. Run one query per vector"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_search_effort(&self) -> Result<()> {
|
||||
if let Some(effort) = self.search_effort
|
||||
&& (!effort.is_finite() || !(0.0..=1.0).contains(&effort))
|
||||
@@ -1370,6 +1461,18 @@ impl VectorQuery {
|
||||
&self.request
|
||||
}
|
||||
|
||||
fn single_search_rerank(&self) -> Option<SingleSearchRerank<'_>> {
|
||||
let base = &self.request.base;
|
||||
if base.full_text_search.is_some() || self.request.query_vector.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(SingleSearchRerank {
|
||||
reranker: base.reranker.as_deref()?,
|
||||
search: SingleSearch::Vector,
|
||||
limit: Some(base.limit.unwrap_or(DEFAULT_TOP_K)),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn into_plain(self) -> Query {
|
||||
Query {
|
||||
parent: self.parent,
|
||||
@@ -1691,11 +1794,12 @@ impl VectorQuery {
|
||||
}
|
||||
|
||||
vector_query.request.base.full_text_search = None;
|
||||
vector_query.request.base.reranker = None;
|
||||
vector_query
|
||||
.share_subquery_filter_with(&mut fts_query)
|
||||
.await?;
|
||||
let (fts_results, vec_results) = try_join!(
|
||||
fts_query.execute_with_options(internal_options.clone()),
|
||||
fts_query.inner_execute_with_options(internal_options.clone()),
|
||||
vector_query.inner_execute_with_options(internal_options)
|
||||
)?;
|
||||
|
||||
@@ -1809,6 +1913,99 @@ impl VectorQuery {
|
||||
}
|
||||
}
|
||||
|
||||
enum SingleSearch<'a> {
|
||||
Vector,
|
||||
FullText(&'a FullTextSearchQuery),
|
||||
}
|
||||
|
||||
struct SingleSearchRerank<'a> {
|
||||
reranker: &'a dyn Reranker,
|
||||
search: SingleSearch<'a>,
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
impl SingleSearchRerank<'_> {
|
||||
async fn output_schema(&self, input: &SchemaRef) -> Result<SchemaRef> {
|
||||
let mut output = match self.reranker.output_schema(input).await? {
|
||||
Some(schema) => schema,
|
||||
None => Arc::new(input.try_with_column(relevance_score_field())?),
|
||||
};
|
||||
let score_fields = output
|
||||
.fields()
|
||||
.iter()
|
||||
.filter(|field| field.name() == RELEVANCE_SCORE);
|
||||
if score_fields.count() != 1 {
|
||||
return Err(Error::Schema {
|
||||
message: format!(
|
||||
"a single-mode reranker must declare exactly one {RELEVANCE_SCORE} field"
|
||||
),
|
||||
});
|
||||
}
|
||||
// The candidate stream is authoritative for query metadata, including
|
||||
// the snapshot used for row-addressed blob reads.
|
||||
if output.metadata() != input.metadata() {
|
||||
Arc::make_mut(&mut output)
|
||||
.metadata
|
||||
.clone_from(input.metadata());
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
candidates: impl Future<Output = Result<SendableRecordBatchStream>> + Send,
|
||||
options: QueryExecutionOptions,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
let rerank = async {
|
||||
let candidates = candidates.await?;
|
||||
let input_schema = candidates.schema();
|
||||
let output_schema = self.output_schema(&input_schema).await?;
|
||||
let batches = candidates.try_collect::<Vec<_>>().await?;
|
||||
let candidates = concat_batches(&input_schema, &batches)?;
|
||||
let mut results = match self.search {
|
||||
SingleSearch::Vector => self.reranker.rerank_vector("", candidates).await?,
|
||||
SingleSearch::FullText(fts) => {
|
||||
self.reranker
|
||||
.rerank_fts(&fts.query.query(), candidates)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
if results.schema().fields() != output_schema.fields() {
|
||||
return Err(Error::Schema {
|
||||
message: format!(
|
||||
"reranker returned fields {:?}, but declared {:?}",
|
||||
results.schema().fields(),
|
||||
output_schema.fields()
|
||||
),
|
||||
});
|
||||
}
|
||||
results
|
||||
.schema_metadata_mut()
|
||||
.clone_from(output_schema.metadata());
|
||||
if let Some(limit) = self.limit
|
||||
&& results.num_rows() > limit
|
||||
{
|
||||
results = results.slice(0, limit);
|
||||
}
|
||||
Ok(single_batch_stream(
|
||||
results,
|
||||
options.max_batch_length as usize,
|
||||
))
|
||||
};
|
||||
|
||||
match options.timeout {
|
||||
Some(timeout) => {
|
||||
tokio::time::timeout(timeout, rerank)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout {
|
||||
message: format!("Query timeout after {} ms", timeout.as_millis()),
|
||||
})?
|
||||
}
|
||||
None => rerank.await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn single_batch_stream(batch: RecordBatch, max_batch_length: usize) -> SendableRecordBatchStream {
|
||||
let schema = batch.schema();
|
||||
if max_batch_length == 0 || batch.num_rows() <= max_batch_length {
|
||||
@@ -1845,9 +2042,25 @@ impl ExecutableQuery for VectorQuery {
|
||||
return Ok(hybrid_result);
|
||||
}
|
||||
|
||||
if let Some(rerank) = self.single_search_rerank() {
|
||||
let candidates =
|
||||
self.inner_execute_with_options(options.without_output_batch_length_limit());
|
||||
return rerank.execute(candidates, options).await;
|
||||
}
|
||||
self.inner_execute_with_options(options).await
|
||||
}
|
||||
|
||||
async fn output_schema(&self) -> Result<SchemaRef> {
|
||||
let input = self
|
||||
.create_plan(QueryExecutionOptions::default())
|
||||
.await?
|
||||
.schema();
|
||||
match self.single_search_rerank() {
|
||||
Some(rerank) => rerank.output_schema(&input).await,
|
||||
None => Ok(input),
|
||||
}
|
||||
}
|
||||
|
||||
async fn explain_plan(&self, verbose: bool) -> Result<String> {
|
||||
let query = AnyQuery::VectorQuery(self.request.clone());
|
||||
self.parent.explain_plan(&query, verbose).await
|
||||
|
||||
@@ -1918,6 +1918,20 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
query: &AnyQuery,
|
||||
options: &QueryExecutionOptions,
|
||||
) -> Result<Vec<Pin<Box<dyn RecordBatchStream + Send>>>> {
|
||||
if let AnyQuery::VectorQuery(query) = query
|
||||
&& query.query_vector.len() > 1
|
||||
&& query.base.reranker.is_some()
|
||||
&& query.base.full_text_search.is_none()
|
||||
{
|
||||
// Older servers execute one independent search per vector.
|
||||
query.validate_rerank_batch(!self.server_version.support_multivector())?;
|
||||
let schema = self.schema().await?;
|
||||
let schema = lance_core::datatypes::Schema::try_from(schema.as_ref())?;
|
||||
let (_, vector_type, _) =
|
||||
query.resolve_vector_column(&schema, query.query_vector[0].len())?;
|
||||
query.validate_rerank_batch(!matches!(vector_type, DataType::List(_)))?;
|
||||
}
|
||||
|
||||
let mut request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/query/", self.identifier))
|
||||
|
||||
@@ -8,6 +8,7 @@ use arrow::{
|
||||
compute::{concat_batches, filter_record_batch},
|
||||
};
|
||||
use arrow_array::{BooleanArray, RecordBatch, UInt64Array};
|
||||
use arrow_schema::{DataType, Field, SchemaRef};
|
||||
use async_trait::async_trait;
|
||||
use lance::dataset::ROW_ID;
|
||||
|
||||
@@ -16,7 +17,11 @@ use crate::error::{Error, Result};
|
||||
pub mod rrf;
|
||||
|
||||
/// column name for reranker relevance score
|
||||
const RELEVANCE_SCORE: &str = "_relevance_score";
|
||||
pub(crate) const RELEVANCE_SCORE: &str = "_relevance_score";
|
||||
|
||||
pub(crate) fn relevance_score_field() -> Field {
|
||||
Field::new(RELEVANCE_SCORE, DataType::Float32, false)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum NormalizeMethod {
|
||||
@@ -47,12 +52,46 @@ impl std::fmt::Display for NormalizeMethod {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface for a reranker. A reranker is used to rerank the results from a
|
||||
/// vector and FTS search. This is useful for combining the results from both
|
||||
/// search methods.
|
||||
/// Reranks the results of vector, full-text, or hybrid search.
|
||||
///
|
||||
/// Implement [`Self::rerank_hybrid`] to combine vector and full-text results.
|
||||
/// Override [`Self::rerank_vector`] and [`Self::rerank_fts`] to support
|
||||
/// single-mode searches. Their default implementations return
|
||||
/// [`Error::NotSupported`].
|
||||
#[async_trait]
|
||||
pub trait Reranker: std::fmt::Debug + Sync + Send {
|
||||
// TODO support vector reranking and FTS reranking. Currently only hybrid reranking is supported.
|
||||
/// Declare the output fields of a single-mode rerank without scoring any rows.
|
||||
///
|
||||
/// Returning `None` keeps the input fields and appends a non-nullable
|
||||
/// Float32 `_relevance_score` field. Return a schema if your vector or
|
||||
/// full-text callback changes the fields in a different way.
|
||||
async fn output_schema(&self, _input: &SchemaRef) -> Result<Option<SchemaRef>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Rerank vector search results, including empty results.
|
||||
///
|
||||
/// The query builder passes an empty query string because it only has the
|
||||
/// query vector. The result must match the fields from [`Self::output_schema`].
|
||||
async fn rerank_vector(
|
||||
&self,
|
||||
_query: &str,
|
||||
_vector_results: RecordBatch,
|
||||
) -> Result<RecordBatch> {
|
||||
Err(Error::NotSupported {
|
||||
message: format!("{:?} does not implement vector-only reranking", self),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rerank full-text search results, including empty results.
|
||||
///
|
||||
/// The query builder passes the full-text query string. The result must
|
||||
/// match the fields from [`Self::output_schema`].
|
||||
async fn rerank_fts(&self, _query: &str, _fts_results: RecordBatch) -> Result<RecordBatch> {
|
||||
Err(Error::NotSupported {
|
||||
message: format!("{:?} does not implement FTS-only reranking", self),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rerank function receives the individual results from the vector and FTS search
|
||||
/// results. You can choose to use any of the results to generate the final results,
|
||||
|
||||
@@ -12,13 +12,17 @@ use arrow_array::{Float32Array, RecordBatch, UInt64Array};
|
||||
use arrow_schema::{DataType, Field, Schema, SortOptions};
|
||||
use async_trait::async_trait;
|
||||
use lance::dataset::ROW_ID;
|
||||
use lance_arrow::RecordBatchExt;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::rerankers::{RELEVANCE_SCORE, Reranker};
|
||||
use crate::rerankers::{RELEVANCE_SCORE, Reranker, relevance_score_field};
|
||||
|
||||
/// Reranks the results using Reciprocal Rank Fusion(RRF) algorithm based
|
||||
/// on the scores of vector and FTS search.
|
||||
/// Reranks search results using Reciprocal Rank Fusion (RRF).
|
||||
///
|
||||
/// For a single ranked list, each row keeps its position and receives
|
||||
/// `1 / (k + rank)` as its relevance score, with ranks starting at 1.
|
||||
/// For hybrid search, RRF sums the contributions from both ranked lists
|
||||
/// for each row and sorts by the combined score.
|
||||
#[derive(Debug)]
|
||||
pub struct RRFReranker {
|
||||
k: f32,
|
||||
@@ -35,6 +39,13 @@ impl RRFReranker {
|
||||
pub fn new(k: f32) -> Self {
|
||||
Self { k }
|
||||
}
|
||||
|
||||
fn rerank_list(&self, results: RecordBatch) -> Result<RecordBatch> {
|
||||
let scores = Float32Array::from_iter_values(
|
||||
(0..results.num_rows()).map(|index| 1.0 / ((index + 1) as f32 + self.k)),
|
||||
);
|
||||
Ok(results.try_with_column(relevance_score_field(), Arc::new(scores))?)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RRFReranker {
|
||||
@@ -45,6 +56,18 @@ impl Default for RRFReranker {
|
||||
|
||||
#[async_trait]
|
||||
impl Reranker for RRFReranker {
|
||||
async fn rerank_vector(
|
||||
&self,
|
||||
_query: &str,
|
||||
vector_results: RecordBatch,
|
||||
) -> Result<RecordBatch> {
|
||||
self.rerank_list(vector_results)
|
||||
}
|
||||
|
||||
async fn rerank_fts(&self, _query: &str, fts_results: RecordBatch) -> Result<RecordBatch> {
|
||||
self.rerank_list(fts_results)
|
||||
}
|
||||
|
||||
async fn rerank_hybrid(
|
||||
&self,
|
||||
_query: &str,
|
||||
|
||||
+121
-24
@@ -19,7 +19,7 @@ use crate::index::scalar::{FtsQuery, Operator as FullTextOperator};
|
||||
use crate::query::{
|
||||
DEFAULT_TOP_K, QueryExecutionOptions, QueryFilter, QueryRequest, Select, VectorQueryRequest,
|
||||
};
|
||||
use crate::utils::{MaxBatchLengthStream, TimeoutStream, default_vector_column};
|
||||
use crate::utils::{MaxBatchLengthStream, TimeoutStream};
|
||||
use arrow::array::{AsArray, FixedSizeListBuilder, Float32Builder};
|
||||
use arrow::datatypes::{Float32Type, UInt8Type};
|
||||
use arrow_array::Array;
|
||||
@@ -312,22 +312,17 @@ pub async fn create_plan(
|
||||
}
|
||||
|
||||
let schema = ds_ref.schema();
|
||||
let mut column = query.column.clone();
|
||||
|
||||
let mut query_vector = query.query_vector.first().cloned();
|
||||
let vector_column = query_vector
|
||||
.as_ref()
|
||||
.map(|vector| query.resolve_vector_column(schema, vector.len()))
|
||||
.transpose()?;
|
||||
let mut is_batch_query = false;
|
||||
if query.query_vector.len() > 1 {
|
||||
if column.is_none() {
|
||||
// Infer a vector column with the same dimension of the query vector.
|
||||
let arrow_schema = Schema::from(schema);
|
||||
column = Some(default_vector_column(
|
||||
&arrow_schema,
|
||||
Some(query.query_vector[0].len() as i32),
|
||||
)?);
|
||||
}
|
||||
let (vector_type, element_type) =
|
||||
lance::index::vector::utils::get_vector_type(schema, column.as_ref().unwrap())?;
|
||||
let is_list_vector = matches!(&vector_type, DataType::List(_));
|
||||
if let Some((_, vector_type, element_type)) = &vector_column
|
||||
&& query.query_vector.len() > 1
|
||||
{
|
||||
let is_list_vector = matches!(vector_type, DataType::List(_));
|
||||
query.validate_rerank_batch(!is_list_vector)?;
|
||||
let is_binary = matches!(element_type, DataType::UInt8);
|
||||
if is_list_vector || (query.base.offset.unwrap_or(0) == 0 && !is_binary) {
|
||||
// Lance distinguishes these cases from the vector column type: a
|
||||
@@ -390,15 +385,7 @@ pub async fn create_plan(
|
||||
|
||||
let mut scanner: Scanner = ds_ref.scan();
|
||||
|
||||
if let Some(query_vector) = query_vector {
|
||||
let column = if let Some(col) = column {
|
||||
col
|
||||
} else {
|
||||
let arrow_schema = Schema::from(schema);
|
||||
default_vector_column(&arrow_schema, Some(query_vector.len() as i32))?
|
||||
};
|
||||
|
||||
let (_, element_type) = lance::index::vector::utils::get_vector_type(schema, &column)?;
|
||||
if let (Some(query_vector), Some((column, _, element_type))) = (query_vector, vector_column) {
|
||||
let is_binary = matches!(element_type, DataType::UInt8);
|
||||
let top_k = query
|
||||
.base
|
||||
@@ -1951,6 +1938,116 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_fts_reranks_namespace_query_table_candidates_once() {
|
||||
use crate::rerankers::{Reranker, rrf::RRFReranker};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FtsNamespace {
|
||||
candidates: bytes::Bytes,
|
||||
calls: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl LanceNamespace for FtsNamespace {
|
||||
fn namespace_id(&self) -> String {
|
||||
"fts-test".to_string()
|
||||
}
|
||||
|
||||
async fn query_table(
|
||||
&self,
|
||||
request: NsQueryTableRequest,
|
||||
) -> lance::Result<bytes::Bytes> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
assert_eq!(request.k, 2);
|
||||
assert_eq!(request.vector.single_vector, Some(vec![]));
|
||||
let fts = request.full_text_query.unwrap();
|
||||
assert_eq!(fts.string_query.unwrap().query, "dog");
|
||||
Ok(self.candidates.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct FtsReranker(AtomicUsize);
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Reranker for FtsReranker {
|
||||
async fn rerank_fts(
|
||||
&self,
|
||||
query: &str,
|
||||
candidates: RecordBatch,
|
||||
) -> Result<RecordBatch> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
assert_eq!(query, "dog");
|
||||
RRFReranker::default().rerank_fts(query, candidates).await
|
||||
}
|
||||
|
||||
async fn rerank_hybrid(
|
||||
&self,
|
||||
_: &str,
|
||||
_: RecordBatch,
|
||||
_: RecordBatch,
|
||||
) -> Result<RecordBatch> {
|
||||
panic!("unexpected hybrid rerank");
|
||||
}
|
||||
}
|
||||
|
||||
let candidates = RecordBatch::try_from_iter([
|
||||
("id", Arc::new(Int32Array::from(vec![42, 7])) as ArrayRef),
|
||||
(
|
||||
"_score",
|
||||
Arc::new(Float32Array::from(vec![2.0, 1.0])) as ArrayRef,
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
let namespace = Arc::new(FtsNamespace {
|
||||
candidates: crate::ipc::batches_to_ipc_file(&[candidates])
|
||||
.unwrap()
|
||||
.into(),
|
||||
calls: AtomicUsize::new(0),
|
||||
});
|
||||
let db = crate::connect("memory://").execute().await.unwrap();
|
||||
let table = db
|
||||
.create_table(
|
||||
"pushed_fts",
|
||||
RecordBatch::try_from_iter([(
|
||||
"id",
|
||||
Arc::new(Int32Array::from(vec![0])) as ArrayRef,
|
||||
)])
|
||||
.unwrap(),
|
||||
)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut native = table.as_native().unwrap().clone();
|
||||
native.namespace_client = Some(namespace.clone());
|
||||
native
|
||||
.pushdown_operations
|
||||
.insert(NamespaceClientPushdownOperation::QueryTable);
|
||||
let table = crate::Table::new(Arc::new(native), table.database().clone());
|
||||
|
||||
let reranker = Arc::new(FtsReranker::default());
|
||||
// This table has no text column or index. Success requires QueryTable.
|
||||
let query = table
|
||||
.query()
|
||||
.full_text_search(FullTextSearchQuery::new("dog".into()))
|
||||
.select(Select::columns(&["id"]))
|
||||
.limit(2)
|
||||
.rerank(reranker.clone());
|
||||
let batches = query
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_i32(&batches), vec![42, 7]);
|
||||
let scores = batches[0]["_relevance_score"].as_primitive::<Float32Type>();
|
||||
assert_eq!(scores.values().as_ref(), &[1.0 / 61.0, 1.0 / 62.0]);
|
||||
assert_eq!(namespace.calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(reranker.0.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_execute_query_pinned_snapshot_with_namespace_pushdown_runs_locally() {
|
||||
use crate::connect;
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use arrow::buffer::OffsetBuffer;
|
||||
use arrow_array::cast::AsArray;
|
||||
use arrow_array::types::{Float32Type, Int32Type};
|
||||
use arrow_array::{
|
||||
Array, ArrayRef, FixedSizeListArray, Int32Array, ListArray, RecordBatch, StringArray,
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use async_trait::async_trait;
|
||||
use futures::TryStreamExt;
|
||||
use lance::dataset::ROW_ID;
|
||||
use lance_index::scalar::FullTextSearchQuery;
|
||||
use lancedb::index::Index;
|
||||
use lancedb::query::{ExecutableQuery, QueryBase, QueryExecutionOptions, Select};
|
||||
use lancedb::rerankers::{Reranker, rrf::RRFReranker};
|
||||
use lancedb::{DistanceType, Error, Result, Table, connect};
|
||||
use tempfile::TempDir;
|
||||
|
||||
const SCORE: &str = "_relevance_score";
|
||||
const SEARCH_VECTOR: &[f32] = &[1.0, 0.0];
|
||||
|
||||
fn search_batch(start: i32, text: Vec<&str>, vectors: Vec<[f32; 2]>) -> RecordBatch {
|
||||
let vector = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
|
||||
vectors.into_iter().map(|v| Some(v.map(Some))),
|
||||
2,
|
||||
);
|
||||
RecordBatch::try_new(
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int32, false),
|
||||
Field::new("text", DataType::Utf8, false),
|
||||
Field::new("vector", vector.data_type().clone(), false),
|
||||
])),
|
||||
vec![
|
||||
Arc::new(Int32Array::from_iter_values(
|
||||
start..start + text.len() as i32,
|
||||
)),
|
||||
Arc::new(StringArray::from(text)),
|
||||
Arc::new(vector),
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn search_table() -> (TempDir, Table) {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let db = connect(directory.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let table = db
|
||||
.create_table(
|
||||
"search",
|
||||
search_batch(1, vec!["dog dog", "cat"], vec![[1.0, 0.0], [2.0, 0.0]]),
|
||||
)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table
|
||||
.add(search_batch(3, vec!["dog in a garden"], vec![[3.0, 0.0]]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table
|
||||
.create_index(&["text"], Index::FTS(Default::default()))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
(directory, table)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn vector_rrf_matches_output_schema_and_keeps_rank_order() {
|
||||
let (_directory, table) = search_table().await;
|
||||
let query = table
|
||||
.vector_search(SEARCH_VECTOR)
|
||||
.unwrap()
|
||||
.select(Select::columns(&["id"]))
|
||||
.limit(2)
|
||||
.rerank(Arc::new(RRFReranker::default()));
|
||||
let schema = query.output_schema().await.unwrap();
|
||||
assert_eq!(
|
||||
schema.field_with_name(SCORE).unwrap().data_type(),
|
||||
&DataType::Float32
|
||||
);
|
||||
assert!(schema.column_with_name(ROW_ID).is_none());
|
||||
|
||||
let mut options = QueryExecutionOptions::default();
|
||||
options.max_batch_length = 1;
|
||||
let results = query.execute_with_options(options).await.unwrap();
|
||||
assert_eq!(results.schema(), schema);
|
||||
let batches = results.try_collect::<Vec<_>>().await.unwrap();
|
||||
assert_eq!(batches.len(), 2);
|
||||
for (batch, (id, score)) in batches.iter().zip([(1, 1.0 / 61.0), (2, 1.0 / 62.0)]) {
|
||||
assert_eq!(batch.schema(), schema);
|
||||
assert_eq!(
|
||||
batch["id"].as_primitive::<Int32Type>().values().as_ref(),
|
||||
&[id]
|
||||
);
|
||||
assert_eq!(
|
||||
batch[SCORE].as_primitive::<Float32Type>().values().as_ref(),
|
||||
&[score]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fts_rrf_preserves_selected_row_ids_and_empty_schema() {
|
||||
let (_directory, table) = search_table().await;
|
||||
let reranker = Arc::new(RRFReranker::default());
|
||||
for (term, expected_ids, expected_scores) in [
|
||||
("dog", &[1, 3][..], &[1.0 / 61.0, 1.0 / 62.0][..]),
|
||||
("absent", &[][..], &[][..]),
|
||||
] {
|
||||
let query = table
|
||||
.query()
|
||||
.full_text_search(FullTextSearchQuery::new(term.into()))
|
||||
.select(Select::columns(&["id"]))
|
||||
.with_row_id()
|
||||
.rerank(reranker.clone());
|
||||
let schema = query.output_schema().await.unwrap();
|
||||
assert!(schema.column_with_name(ROW_ID).is_some());
|
||||
let mut results = query.execute().await.unwrap();
|
||||
assert_eq!(results.schema(), schema);
|
||||
let batch = results.try_next().await.unwrap().unwrap();
|
||||
assert_eq!(batch.schema(), schema);
|
||||
assert_eq!(
|
||||
batch["id"].as_primitive::<Int32Type>().values().as_ref(),
|
||||
expected_ids
|
||||
);
|
||||
assert_eq!(
|
||||
batch[SCORE].as_primitive::<Float32Type>().values().as_ref(),
|
||||
expected_scores
|
||||
);
|
||||
assert!(results.try_next().await.unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct TrackingReranker {
|
||||
calls: Mutex<Vec<(&'static str, String)>>,
|
||||
pause_vector: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Reranker for TrackingReranker {
|
||||
async fn rerank_vector(&self, query: &str, results: RecordBatch) -> Result<RecordBatch> {
|
||||
self.calls.lock().unwrap().push(("vector", query.into()));
|
||||
if self.pause_vector {
|
||||
// Pause after the candidates are ready, then let time advance inside the callback.
|
||||
tokio::time::pause();
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
}
|
||||
RRFReranker::default().rerank_vector(query, results).await
|
||||
}
|
||||
|
||||
async fn rerank_fts(&self, query: &str, results: RecordBatch) -> Result<RecordBatch> {
|
||||
self.calls.lock().unwrap().push(("fts", query.into()));
|
||||
RRFReranker::default().rerank_fts(query, results).await
|
||||
}
|
||||
|
||||
async fn rerank_hybrid(
|
||||
&self,
|
||||
query: &str,
|
||||
vector: RecordBatch,
|
||||
fts: RecordBatch,
|
||||
) -> Result<RecordBatch> {
|
||||
self.calls.lock().unwrap().push(("hybrid", query.into()));
|
||||
RRFReranker::default()
|
||||
.rerank_hybrid(query, vector, fts)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_dispatches_only_the_matching_reranker_callback() {
|
||||
let (_directory, table) = search_table().await;
|
||||
let reranker = Arc::new(TrackingReranker::default());
|
||||
let fts = table
|
||||
.query()
|
||||
.full_text_search(FullTextSearchQuery::new("dog".into()));
|
||||
let vector = table
|
||||
.vector_search(SEARCH_VECTOR)
|
||||
.unwrap()
|
||||
.rerank(reranker.clone());
|
||||
vector.output_schema().await.unwrap();
|
||||
assert!(reranker.calls.lock().unwrap().is_empty());
|
||||
vector.execute().await.unwrap();
|
||||
fts.clone()
|
||||
.rerank(reranker.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
fts.nearest_to(SEARCH_VECTOR)
|
||||
.unwrap()
|
||||
.rerank(reranker.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
*reranker.calls.lock().unwrap(),
|
||||
[
|
||||
("vector", String::new()),
|
||||
("fts", "dog".into()),
|
||||
("hybrid", "dog".into())
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn vector_query_timeout_covers_the_reranker_callback() {
|
||||
let (_directory, table) = search_table().await;
|
||||
let reranker = Arc::new(TrackingReranker {
|
||||
pause_vector: true,
|
||||
..Default::default()
|
||||
});
|
||||
let query = table
|
||||
.vector_search(SEARCH_VECTOR)
|
||||
.unwrap()
|
||||
.rerank(reranker.clone());
|
||||
let mut options = QueryExecutionOptions::default();
|
||||
options.timeout = Some(Duration::from_secs(10));
|
||||
assert!(matches!(
|
||||
query.execute_with_options(options).await,
|
||||
Err(Error::Timeout { .. })
|
||||
));
|
||||
assert_eq!(*reranker.calls.lock().unwrap(), [("vector", String::new())]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn vector_rerank_accepts_a_multivector_list_but_rejects_independent_queries() {
|
||||
let (_directory, table) = search_table().await;
|
||||
let reranker = Arc::new(RRFReranker::default());
|
||||
let batch_query = table
|
||||
.vector_search(SEARCH_VECTOR)
|
||||
.unwrap()
|
||||
.add_query_vector(&[0.0, 1.0])
|
||||
.unwrap()
|
||||
.rerank(reranker.clone());
|
||||
assert!(matches!(
|
||||
batch_query.output_schema().await,
|
||||
Err(Error::NotSupported { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
batch_query.execute().await,
|
||||
Err(Error::NotSupported { .. })
|
||||
));
|
||||
|
||||
let db = connect("memory://").execute().await.unwrap();
|
||||
let vectors = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
|
||||
[Some([Some(1.0), Some(0.0)]), Some([Some(0.0), Some(1.0)])],
|
||||
2,
|
||||
);
|
||||
let column = ListArray::new(
|
||||
Arc::new(Field::new("item", vectors.data_type().clone(), true)),
|
||||
OffsetBuffer::new(vec![0, 2].into()),
|
||||
Arc::new(vectors),
|
||||
None,
|
||||
);
|
||||
let batch = RecordBatch::try_from_iter([
|
||||
("vector", Arc::new(column) as ArrayRef),
|
||||
(
|
||||
"query_index",
|
||||
Arc::new(StringArray::from(vec!["user data"])) as ArrayRef,
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
let table = db
|
||||
.create_table("multivector", batch)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let query = table
|
||||
.vector_search(SEARCH_VECTOR)
|
||||
.unwrap()
|
||||
.add_query_vector(&[0.0, 1.0])
|
||||
.unwrap()
|
||||
.column("vector")
|
||||
.distance_type(DistanceType::Cosine)
|
||||
.select(Select::columns(&["query_index"]))
|
||||
.rerank(reranker);
|
||||
let schema = query.output_schema().await.unwrap();
|
||||
assert_eq!(
|
||||
schema.field_with_name("query_index").unwrap().data_type(),
|
||||
&DataType::Utf8
|
||||
);
|
||||
let mut results = query.execute().await.unwrap();
|
||||
assert_eq!(results.schema(), schema);
|
||||
let result = results.try_next().await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
result["query_index"].as_string::<i32>().value(0),
|
||||
"user data"
|
||||
);
|
||||
assert_eq!(
|
||||
result[SCORE]
|
||||
.as_primitive::<Float32Type>()
|
||||
.values()
|
||||
.as_ref(),
|
||||
&[1.0 / 61.0]
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user