diff --git a/python/python/lancedb/rerankers/base.py b/python/python/lancedb/rerankers/base.py index 966f23eeb..a675aff5d 100644 --- a/python/python/lancedb/rerankers/base.py +++ b/python/python/lancedb/rerankers/base.py @@ -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": diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index 8685f2792..30aa73b63 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -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( {