mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix(python): preserve Arrow values when merging hybrid reranker scores (#5323)
An Embedded hybrid query using `RRFReranker(return_score="all")` can change unrelated result columns. On 0.42.1, a `time64[ns]` value of 1001 ns comes back as 1000 ns with pandas installed. A fixed-shape tensor created with `FixedShapeTensorArray.from_numpy_ndarray` raises `NotImplementedError` during the same query. Both columns round-trip with the default relevance score. The shared reranker merge converts every result row to a Python object to combine `_distance` and `_score`. This change looks up row positions by `_rowid` and takes rows and scores directly from the Arrow columns. A hit in both searches keeps the vector row and receives the FTS score. The regression tests run a hybrid search against an in-memory table and compare the returned Arrow arrays with the inputs. ### Testing - Both new cases failed before the change and passed after it. Also verified the fix with pandas uninstalled. - The two new cases and both existing rank-fusion score tests also passed with the minimum supported PyArrow 16.0.0. - Ran the checkout's rerankers with the 0.42.1 SDK and native extension. `test_rerankers.py` and `test_typesafe_reranker.py` had 158 passes and 17 skips. Including `test_hybrid_query.py` gave 187 passes and 17 skips, with the same 14 failures seen before this change against the release SDK. - Python Ruff checks and formatting for both changed files passed.
This commit is contained in:
@@ -243,35 +243,29 @@ class Reranker(ABC):
|
||||
This op is slower than just keeping relevance score but can be useful
|
||||
for debugging.
|
||||
"""
|
||||
combined_schema = pa.unify_schemas([vector_results.schema, fts_results.schema])
|
||||
# add nulls to fts results for _distance
|
||||
if "_distance" not in fts_results.column_names:
|
||||
fts_results = fts_results.append_column(
|
||||
"_distance",
|
||||
pa.array([None] * len(fts_results), type=pa.float32()),
|
||||
)
|
||||
# add nulls to vector results for _score
|
||||
if "_score" not in vector_results.column_names:
|
||||
vector_results = vector_results.append_column(
|
||||
"_score",
|
||||
pa.array([None] * len(vector_results), type=pa.float32()),
|
||||
)
|
||||
|
||||
# combine them and fill the scores
|
||||
vector_results_dict = {row["_rowid"]: row for row in vector_results.to_pylist()}
|
||||
fts_results_dict = {row["_rowid"]: row for row in fts_results.to_pylist()}
|
||||
|
||||
# merge them into vector_results
|
||||
for key, value in fts_results_dict.items():
|
||||
if key in vector_results_dict:
|
||||
vector_results_dict[key]["_score"] = value["_score"]
|
||||
else:
|
||||
vector_results_dict[key] = value
|
||||
|
||||
combined = pa.Table.from_pylist(
|
||||
list(vector_results_dict.values()), schema=combined_schema
|
||||
combined = pa.concat_tables(
|
||||
[vector_results, fts_results], **self._concat_tables_args
|
||||
)
|
||||
return combined
|
||||
if combined.num_rows == 0:
|
||||
return combined
|
||||
|
||||
row_ids = combined["_rowid"].to_pylist()
|
||||
vector_indices = {
|
||||
row_id: i for i, row_id in enumerate(row_ids[: len(vector_results)])
|
||||
}
|
||||
# Keep the first-seen ID order and the last occurrence within each search.
|
||||
# For shared IDs the payload comes from vector search and the score from FTS.
|
||||
score_indices = {row_id: i for i, row_id in enumerate(row_ids)}
|
||||
result = combined.take(
|
||||
[vector_indices.get(row_id, i) for row_id, i in score_indices.items()]
|
||||
)
|
||||
score_idx = combined.schema.get_field_index("_score")
|
||||
if score_idx >= 0:
|
||||
scores = combined["_score"].take(list(score_indices.values()))
|
||||
result = result.set_column(
|
||||
score_idx, combined.schema.field(score_idx), scores
|
||||
)
|
||||
return result
|
||||
|
||||
def _keep_relevance_score(self, combined_results: pa.Table):
|
||||
if self.score == "relevance":
|
||||
|
||||
@@ -524,6 +524,43 @@ def test_rank_fusion_return_score_all_keeps_both_scores(reranker_cls):
|
||||
assert rows[3]["_score"] == pytest.approx(4.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
pa.array([1001, 2002, 3003], type=pa.time64("ns")),
|
||||
pa.FixedShapeTensorArray.from_numpy_ndarray(
|
||||
np.arange(12, dtype=np.float32).reshape(3, 2, 2)
|
||||
),
|
||||
],
|
||||
ids=["nanosecond-time", "tensor"],
|
||||
)
|
||||
def test_hybrid_all_scores_preserves_arrow_payload(mem_db, payload):
|
||||
from lancedb.index import FTS
|
||||
|
||||
table = mem_db.create_table(
|
||||
"documents",
|
||||
pa.table(
|
||||
{
|
||||
"id": [0, 1, 2],
|
||||
"text": ["apple", "apple tart", "orange"],
|
||||
"vector": pa.array([[1, 2], [3, 4], [5, 6]], pa.list_(pa.float32(), 2)),
|
||||
"payload": payload,
|
||||
}
|
||||
),
|
||||
)
|
||||
table.create_index("text", config=FTS())
|
||||
result = (
|
||||
table.search(query_type="hybrid")
|
||||
.text("apple")
|
||||
.vector([1, 2])
|
||||
.rerank(RRFReranker(return_score="all"))
|
||||
.limit(3)
|
||||
.to_arrow()
|
||||
.sort_by("id")
|
||||
)
|
||||
assert result["payload"].combine_chunks().equals(payload)
|
||||
|
||||
|
||||
def test_rrf_reranker_distance():
|
||||
data = pa.table(
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user