|
11 | 11 | import logging |
12 | 12 | import re |
13 | 13 | from collections.abc import Callable, Sequence |
| 14 | +from importlib.metadata import PackageNotFoundError |
| 15 | +from importlib.metadata import version as package_version |
14 | 16 | from typing import Any, ParamSpec, TypeVar, cast |
15 | 17 |
|
16 | 18 | from pymilvus import DataType, MilvusClient |
|
46 | 48 | _UNSAFE_COLLECTION_CHARS = re.compile(r"[^A-Za-z0-9_]") |
47 | 49 |
|
48 | 50 |
|
| 51 | +def _uses_lite_3_cosine_distance(uri: str) -> bool: |
| 52 | + """Return whether the client uses Milvus Lite 3.0 distance semantics.""" |
| 53 | + if "://" in uri: |
| 54 | + return False |
| 55 | + try: |
| 56 | + return package_version("milvus-lite") in {"3.0", "3.0.0"} |
| 57 | + except PackageNotFoundError: |
| 58 | + return False |
| 59 | + |
| 60 | + |
49 | 61 | class MilvusVectorStore(VectorStore): |
50 | 62 | """ |
51 | 63 | Milvus implementation of the VectorStore interface. |
@@ -364,6 +376,10 @@ async def query( |
364 | 376 | "limit": top_k, |
365 | 377 | "search_params": {"metric_type": DISTANCE_METRIC}, |
366 | 378 | } |
| 379 | + if settings.VECTOR_STORE.MILVUS_CONSISTENCY_LEVEL: |
| 380 | + search_kwargs["consistency_level"] = ( |
| 381 | + settings.VECTOR_STORE.MILVUS_CONSISTENCY_LEVEL |
| 382 | + ) |
367 | 383 | if output_fields is not None: |
368 | 384 | search_kwargs["output_fields"] = output_fields |
369 | 385 |
|
@@ -399,11 +415,16 @@ async def query( |
399 | 415 |
|
400 | 416 | def _hit_cosine_distance(self, hit: dict[str, Any]) -> float: |
401 | 417 | """Return Honcho cosine distance from a Milvus search hit.""" |
402 | | - if "distance" in hit: |
403 | | - return float(hit["distance"]) |
404 | | - if "score" in hit: |
405 | | - return 1.0 - float(hit["score"]) |
406 | | - return 0.0 |
| 418 | + if "distance" not in hit: |
| 419 | + return 0.0 |
| 420 | + |
| 421 | + raw_distance = float(hit["distance"]) |
| 422 | + # Milvus Lite 3.0 reports COSINE distance while Milvus server and |
| 423 | + # Zilliz Cloud report COSINE similarity. Keep this workaround scoped |
| 424 | + # to the affected Lite release: https://github.com/milvus-io/milvus-lite/issues/343 |
| 425 | + if _uses_lite_3_cosine_distance(settings.VECTOR_STORE.MILVUS_URI): |
| 426 | + return raw_distance |
| 427 | + return 1.0 - raw_distance |
407 | 428 |
|
408 | 429 | def _output_fields(self, include_attributes: bool | list[str]) -> list[str] | None: |
409 | 430 | """Translate Honcho projection settings to Milvus output fields.""" |
|
0 commit comments