hybrid_search.py

파일 다운로드

"""RRF: 서로 다른 점수를 더하지 않고 순위를 결합한다."""


def hybrid_search(keyword_rows, vector_rows, top_k=3, rank_constant=60):
    if not isinstance(top_k, int) or not 1 <= top_k <= 20 or rank_constant < 0:
        raise ValueError("top_k는 1~20, rank_constant는 0 이상입니다.")
    combined = {}
    for ranking in (keyword_rows, vector_rows):
        seen = set()
        for row in ranking:
            key = row["chunk_id"]
            if key in seen:
                continue
            seen.add(key)
            item = combined.setdefault(key, {"chunk_id": key, "document_id": row["document_id"],
                                             "score": 0.0, "method": "hybrid"})
            item["score"] += 1 / (rank_constant + row["rank"])
    ordered = sorted(combined.values(), key=lambda row: (-row["score"], row["chunk_id"]))
    return [dict(row, rank=rank) for rank, row in enumerate(ordered[:top_k], 1)]