Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions semantica/vector_store/milvus_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,19 @@ def search(
raise ProcessingError("Milvus not available")

try:
# Ensure "metadata" is always fetched; merge with any caller-supplied
# output_fields so that passing output_fields=["vector"] via **options
# does not raise a duplicate-keyword TypeError.
caller_fields = options.pop("output_fields", []) or []
merged_output_fields = list({"metadata", *caller_fields})

search_results = self.collection.search(
data=[v.tolist() for v in vectors],
anns_field=anns_field,
param=param,
limit=limit,
expr=expr,
output_fields=merged_output_fields,
**options,
)

Expand All @@ -204,11 +211,11 @@ def search(
"id": hit.id,
"distance": hit.distance,
"score": 1.0 / (1.0 + max(0.0, hit.distance)),
# Milvus collection schema stores only id+vector; no
# metadata field is defined in create_collection().
# Return empty dict — a future schema migration that
# adds a metadata JSON field is tracked separately.
"metadata": {},
# The collection schema defines a JSON metadata field
# (see create_collection()). Return the stored value
# so callers receive the same metadata as get_metadata()
# and filter_by_metadata().
"metadata": hit.entity.get("metadata") or {},
Comment thread
ZohaibHassan16 marked this conversation as resolved.
Resolved
"vector": None,
}
)
Expand Down
139 changes: 139 additions & 0 deletions tests/vector_store/test_milvus_store_search_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""Tests for MilvusCollection.search() metadata fix (#1330).

The schema produced by create_collection() includes a JSON `metadata` field.
Before the fix, search() hardcoded ``"metadata": {}`` regardless of what was
stored. After the fix it passes ``output_fields=["metadata"]`` to the Milvus
SDK and reads the actual value from ``hit.entity.get("metadata")``.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional
from unittest.mock import MagicMock, patch

import numpy as np
import pytest


# ---------------------------------------------------------------------------
# Helpers — minimal stubs so we never need a real Milvus server
# ---------------------------------------------------------------------------


def _make_hit(id_: str, distance: float, metadata: Optional[Dict[str, Any]]) -> MagicMock:
"""Return a mock Milvus search hit with a populated entity."""
hit = MagicMock()
hit.id = id_
hit.distance = distance
hit.entity.get = MagicMock(side_effect=lambda key, default=None: metadata if key == "metadata" else default)
return hit


def _make_collection(hits_per_query: List[List[MagicMock]]) -> MagicMock:
"""Return a mock Milvus Collection whose search() yields *hits_per_query*."""
collection = MagicMock()
collection.search.return_value = hits_per_query
return collection


# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("milvus_available", [True])
def test_search_returns_stored_metadata(milvus_available: bool) -> None:
"""search() must return the metadata stored in the collection, not {}."""
stored_meta = {"category": "science", "score": 0.95}
hit = _make_hit("vec-1", 0.1, stored_meta)
collection = _make_collection([[hit]])

with patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", milvus_available):
from semantica.vector_store.milvus_store import MilvusCollection

mc = MilvusCollection.__new__(MilvusCollection)
mc.collection = collection

results = mc.search(
vectors=[np.zeros(4)],
anns_field="vector",
param={"metric_type": "L2", "params": {"nprobe": 10}},
limit=5,
)

assert isinstance(results, list)
assert len(results) == 1
assert results[0]["id"] == "vec-1"
assert results[0]["metadata"] == stored_meta, (
"search() should return the stored metadata, not a hardcoded empty dict"
)


def test_search_requests_metadata_output_field() -> None:
"""The underlying collection.search() call must include 'metadata' in output_fields."""
hit = _make_hit("vec-2", 0.2, {"source": "test"})
collection = _make_collection([[hit]])

with patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True):
from semantica.vector_store.milvus_store import MilvusCollection

mc = MilvusCollection.__new__(MilvusCollection)
mc.collection = collection

mc.search(
vectors=[np.zeros(4)],
anns_field="vector",
param={"metric_type": "L2", "params": {"nprobe": 10}},
limit=3,
)

call_kwargs = collection.search.call_args
output_fields = call_kwargs.kwargs.get("output_fields") or call_kwargs[1].get("output_fields")
assert output_fields is not None and "metadata" in output_fields, (
"search() must pass output_fields=['metadata'] to the Milvus SDK"
)


def test_search_falls_back_to_empty_dict_when_metadata_is_none() -> None:
"""If the entity has no metadata (e.g. legacy record), return {} not None."""
hit = _make_hit("vec-3", 0.5, None)
collection = _make_collection([[hit]])

with patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True):
from semantica.vector_store.milvus_store import MilvusCollection

mc = MilvusCollection.__new__(MilvusCollection)
mc.collection = collection

results = mc.search(
vectors=[np.zeros(4)],
anns_field="vector",
param={"metric_type": "L2", "params": {"nprobe": 10}},
limit=1,
)

assert results[0]["metadata"] == {}, "None metadata from entity should fall back to {}"


def test_search_score_calculation() -> None:
"""Verify score = 1/(1 + max(0, distance)) and distance is preserved."""
distance = 0.4
hit = _make_hit("vec-4", distance, {})
collection = _make_collection([[hit]])

with patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True):
from semantica.vector_store.milvus_store import MilvusCollection

mc = MilvusCollection.__new__(MilvusCollection)
mc.collection = collection

results = mc.search(
vectors=[np.zeros(4)],
anns_field="vector",
param={"metric_type": "L2", "params": {"nprobe": 10}},
limit=1,
)

expected_score = 1.0 / (1.0 + distance)
assert abs(results[0]["score"] - expected_score) < 1e-9
assert results[0]["distance"] == distance
2 changes: 2 additions & 0 deletions tests/vector_store/test_search_result_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ def test_milvus_search_canonical_schema(self):
mock_hit = MagicMock()
mock_hit.id = 42
mock_hit.distance = 0.15
# entity.get("metadata") returns None so the `or {}` fallback yields {}
mock_hit.entity.get.return_value = None

mock_collection.search.return_value = [[mock_hit]]

Expand Down
2 changes: 2 additions & 0 deletions tests/vector_store/test_vector_store_deepdive.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ def test_milvus_store(self, mock_collection_schema, mock_field_schema, mock_data
mock_hit = MagicMock()
mock_hit.id = 1
mock_hit.distance = 0.1
# entity.get("metadata") returns None so the `or {}` fallback yields {}
mock_hit.entity.get.return_value = None
mock_collection_instance.search.return_value = [[mock_hit]]

# Test Init
Expand Down