diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 650584d46..94f8f0149 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -3491,7 +3491,9 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): fts_results = fts_results.set_column( score_i, fts_results.field(score_i), - LanceHybridQueryBuilder._normalize_scores(fts_results.column(score_i)), + LanceHybridQueryBuilder._normalize_scores( + fts_results.column(score_i), tie_value=1.0 + ), ) results = reranker.rerank_hybrid(fts_query, vector_results, fts_results) @@ -3552,7 +3554,9 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): return results @staticmethod - def _normalize_scores(scores: pa.Array, invert=False) -> pa.Array: + def _normalize_scores( + scores: pa.Array, invert=False, tie_value: float = 0.0 + ) -> pa.Array: if len(scores) == 0: return scores # normalize the scores by subtracting the min and dividing by the max @@ -3561,9 +3565,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): if not pc.equal(rng, pa.scalar(0.0)).as_py(): scores = pc.divide(pc.subtract(scores, min), rng) - elif not pc.equal(max, pa.scalar(0.0)).as_py(): - # If rng is 0, then we at least want the scores to be 0 - scores = pc.subtract(scores, min) + else: + # All scores are equal, so they are equally relevant. Distances + # tie at 0 (best), while higher-is-better scores tie at 1. + scores = pc.add(pc.subtract(scores, min), pa.scalar(tie_value, scores.type)) if invert: scores = pc.subtract(1, scores) diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index ec6060db3..7d5fbb3e2 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -604,6 +604,37 @@ def test_normalize_scores(): ) +@pytest.mark.parametrize("normalize", ["score", "rank"]) +def test_hybrid_single_fts_match_keeps_fts_weight(tmp_path, normalize): + from lancedb.rerankers import LinearCombinationReranker + + db = lancedb.connect(tmp_path) + table = db.create_table( + "test", + [ + {"text": "apple banana", "vector": [0.0, 0.0]}, + {"text": "zebra unicorn", "vector": [0.1, 0.0]}, + {"text": "cherry grape", "vector": [5.0, 5.0]}, + ], + ) + table.create_fts_index("text") + + results = ( + table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("zebra") + .rerank(LinearCombinationReranker(weight=0.3), normalize=normalize) + .limit(3) + .to_arrow() + ) + + assert results["text"].to_pylist() == [ + "zebra unicorn", + "apple banana", + "cherry grape", + ] + + def test_hybrid_query_rejects_query_with_vector(sync_table: Table): # Pins the full message: the space between "hybrid search." and "But" is # load-bearing (see the _validate_query literal concatenation).