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:
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user