diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index bc1561a3e3f..60c9624f181 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -335,10 +335,65 @@ Indexes only apply when Feast creates a collection. For an existing collection w logs a warning. To add them, run `feast teardown` and `feast apply`, then materialize again, or use the staged cutover described under [Field types](#field-types). +## Text analysis + +Milvus can split a `String` feature into tokens when it stores it, so that a `TEXT_MATCH` filter +finds rows by token. Declare it with field tags, and Feast sets it up when it creates the +collection: + +```python +Field( + name="title", + dtype=String, + tags={ + "milvus.analyzer_params": '{"tokenizer": "whitespace"}', + "milvus.enable_match": "true", + }, +), +``` + +`milvus.analyzer_params` is a JSON object with the field's analyzer. Without it, Milvus uses its +standard analyzer. `milvus.enable_match: "true"` builds the token index that `TEXT_MATCH` needs. +Both tags apply only to `String` features and need Milvus 2.5 or later. Milvus Lite accepts both +tags but does not apply them: its `TEXT_MATCH` works on any `String` column and always uses the +standard analyzer. + +`milvus.bm25: "true"` on a `String` feature makes Milvus score it with BM25, using its analyzer +(`milvus.analyzer_params`, or the standard one). It needs Milvus 2.5 or later. Feast adds a +`SPARSE_FLOAT_VECTOR` field `_bm25`, a BM25 function `_bm25_fn` that fills it from +the field's tokens, and a `SPARSE_INVERTED_INDEX` named `bm25_index_`. +`milvus.bm25_index_params` passes a JSON object of build parameters to that index, and requires +`milvus.bm25: "true"`: + +```python +Field( + name="title", + dtype=String, + tags={ + "milvus.bm25": "true", + "milvus.bm25_index_params": '{"inverted_index_algo": "TAAT_NAIVE", "bm25_b": 0.3}', + }, +), +``` + +Milvus computes the `_bm25` values on every write, so Feast never writes them, and they are +not features to request. No feature may be named `_bm25`. With `milvus.bm25`, Milvus Lite +accepts only the `standard` and `jieba` tokenizers. + +Feast itself does not query the tokens or the BM25 field: `retrieve_online_documents_v2` filters a +`query_string` with `LIKE`, and Feast filters have no `TEXT_MATCH` operator. Query the collection +with a Milvus client to use them. + +The settings only apply when Feast creates a collection. Feast does not compare analyzer or match +settings with an existing collection. A missing `_bm25` field is reported as a +[schema mismatch](#schema-mismatch), and a missing BM25 index as a missing index. To change any of +them, run `feast teardown` and `feast apply`, then materialize again. + ## Feature views without vectors Milvus requires every collection to have a vector field. For feature views that have no vector -feature, Feast adds a 2-dimensional `_placeholder_vector` field with a FLAT index and fills it with zeros. +feature and no `milvus.bm25` field, Feast adds a 2-dimensional `_placeholder_vector` field with a +FLAT index and fills it with zeros. It is never returned or searched. ## Functionality Matrix diff --git a/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py b/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py index 5e8dfa069d0..de4baa76a89 100644 --- a/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py +++ b/sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py @@ -12,6 +12,8 @@ CollectionSchema, DataType, FieldSchema, + Function, + FunctionType, MilvusClient, ) from pymilvus.client.types import LoadState @@ -395,7 +397,9 @@ def _get_or_create_collection( use_typed = config.online_store.enable_openai_compatible_store partition_key = _partition_key_name(config.online_store, table) entity_columns = {column.name for column in table.entity_columns} - scalar_indexes: List[Dict[str, Any]] = [] + tag_indexes: List[Dict[str, Any]] = [] + bm25_outputs: List[FieldSchema] = [] + functions: List[Function] = [] for field in fields_to_add: spec = _column_spec( field, @@ -408,7 +412,7 @@ def _get_or_create_collection( f"Field '{field.name}': Array(Bool) cannot be a vector field," " Milvus binary vectors are not supported." ) - nullable = _nullable_tag(field) + nullable = _boolean_tag(field, "milvus.nullable") if nullable is None: nullable = spec.get("nullable", False) if nullable and ( @@ -423,10 +427,31 @@ def _get_or_create_collection( spec.pop("nullable", None) if nullable: spec["nullable"] = True - scalar_indexes.extend(_scalar_index_specs(field, spec["dtype"])) + spec.update(_text_analysis_params(field)) + tag_indexes.extend(_scalar_index_specs(field, spec["dtype"])) fields.append(FieldSchema(name=field.name, **spec)) + bm25 = _bm25_specs(field) + if bm25 is not None: + output, function, index = bm25 + bm25_outputs.append(output) + functions.append(function) + tag_indexes.append(index) + # PyMilvus accepts duplicate field names, so a clash would go unnoticed. + names = {f.name for f in fields} + for output in bm25_outputs: + if output.name in names: + raise ValueError( + f"Field '{output.name}' has the name of a milvus.bm25 output:" + " rename it." + ) + fields.extend(bm25_outputs) has_vector_field = any( - f.dtype in (DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR) + f.dtype + in ( + DataType.FLOAT_VECTOR, + DataType.BINARY_VECTOR, + DataType.SPARSE_FLOAT_VECTOR, + ) for f in fields ) if not has_vector_field: @@ -440,7 +465,9 @@ def _get_or_create_collection( if partition_key: _mark_partition_key(fields, partition_key, table.name) schema = CollectionSchema( - fields=fields, description="Feast feature view data" + fields=fields, + functions=functions, + description="Feast feature view data", ) collection_exists = self.client.has_collection( collection_name=collection_name @@ -476,8 +503,8 @@ def _get_or_create_collection( index_type="FLAT", index_name=f"vector_index_{vector_field.name}", ) - for scalar_index in scalar_indexes: - index_params.add_index(**scalar_index) + for tag_index in tag_indexes: + index_params.add_index(**tag_index) # Every collection has at least one vector field, and every # vector field is indexed, so passing the index params here # makes Milvus create the indexes and load the collection. @@ -491,10 +518,10 @@ def _get_or_create_collection( ) else: self._ensure_loaded(collection_name) - _warn_if_scalar_indexes_missing( + _warn_if_tag_indexes_missing( self.client, collection_name, - [index["index_name"] for index in scalar_indexes], + [index["index_name"] for index in tag_indexes], ) description = self.client.describe_collection(collection_name) if collection_exists: @@ -531,7 +558,13 @@ def online_write_batch( collection = self._get_or_create_collection(config, table) entity_batch_to_insert = [] unique_entities: dict[str, dict[str, Any]] = {} - required_fields = {field["name"] for field in collection["fields"]} + # Milvus computes function outputs, such as BM25 vectors, and PyMilvus + # rejects rows that carry them. + required_fields = { + field["name"] + for field in collection["fields"] + if not field.get("is_function_output") + } collection_field_types = { field["name"]: field["type"] for field in collection["fields"] } @@ -864,13 +897,16 @@ def retrieve_online_documents_v2( # Find the vector search field if we need it ann_search_field = None if embedding is not None: - for field in collection["fields"]: - if ( - field["type"] in [DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR] - and field["name"] in output_fields - ): - ann_search_field = field["name"] - break + vector_fields = [ + field["name"] + for field in collection["fields"] + if field["type"] in [DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR] + ] + requested = [name for name in vector_fields if name in output_fields] + # Name the only vector field even when it isn't requested: Milvus + # cannot infer it once the collection also has a BM25 output. + if requested or len(vector_fields) == 1: + ann_search_field = (requested or vector_fields)[0] if filters and filters_contain_numeric_comparison(filters): collection_field_types = { @@ -1545,7 +1581,59 @@ def _scalar_index_specs(field: Field, dtype: DataType) -> List[Dict[str, Any]]: return specs -def _warn_if_scalar_indexes_missing( +def _text_analysis_params(field: Field) -> Dict[str, Any]: + """The analyzer settings that the ``milvus.analyzer_params``, + ``milvus.enable_match`` and ``milvus.bm25`` tags declare.""" + analyzer_params = _json_tag(field, "milvus.analyzer_params", dict) + enable_match = _boolean_tag(field, "milvus.enable_match") + bm25 = _boolean_tag(field, "milvus.bm25") + if analyzer_params is None and not enable_match and not bm25: + return {} + # Other types are stored as VARCHAR too, but their text is not meant to be analyzed. + if from_feast_type(field.dtype) != ValueType.STRING: + raise ValueError( + f"Field '{field.name}' has text analysis tags but is not a String feature" + ) + params: Dict[str, Any] = {"enable_analyzer": True} + if analyzer_params is not None: + params["analyzer_params"] = analyzer_params + if enable_match: + params["enable_match"] = True + return params + + +def _bm25_specs( + field: Field, +) -> Optional[Tuple[FieldSchema, Function, Dict[str, Any]]]: + """The sparse output, BM25 function and index that the ``milvus.bm25`` tag declares.""" + params = _json_tag(field, "milvus.bm25_index_params", dict) + if not _boolean_tag(field, "milvus.bm25"): + if params is not None: + raise ValueError( + f"Field '{field.name}' has a milvus.bm25_index_params tag" + " without milvus.bm25" + ) + return None + output = f"{field.name}_bm25" + return ( + FieldSchema(name=output, dtype=DataType.SPARSE_FLOAT_VECTOR), + Function( + name=f"{output}_fn", + input_field_names=[field.name], + output_field_names=[output], + function_type=FunctionType.BM25, + ), + { + "field_name": output, + "index_type": "SPARSE_INVERTED_INDEX", + "index_name": f"bm25_index_{field.name}", + "metric_type": "BM25", + "params": params or {}, + }, + ) + + +def _warn_if_tag_indexes_missing( client: MilvusClient, collection_name: str, index_names: List[str] ) -> None: if not index_names: @@ -1561,13 +1649,13 @@ def _warn_if_scalar_indexes_missing( ) -def _nullable_tag(field: Field) -> Optional[bool]: - if "milvus.nullable" not in field.tags: +def _boolean_tag(field: Field, tag: str) -> Optional[bool]: + if tag not in field.tags: return None - value = field.tags["milvus.nullable"].lower() + value = field.tags[tag].lower() if value not in ("true", "false"): raise ValueError( - f"Field '{field.name}' has invalid milvus.nullable tag" - f" '{field.tags['milvus.nullable']}': must be 'true' or 'false'." + f"Field '{field.name}' has invalid {tag} tag" + f" '{field.tags[tag]}': must be 'true' or 'false'." ) return value == "true" diff --git a/sdk/python/tests/integration/online_store/test_milvus_remote.py b/sdk/python/tests/integration/online_store/test_milvus_remote.py index db277db102f..fb922522a3d 100644 --- a/sdk/python/tests/integration/online_store/test_milvus_remote.py +++ b/sdk/python/tests/integration/online_store/test_milvus_remote.py @@ -619,11 +619,24 @@ def test_native_complex_types_filters_and_tag_indexes( Field(name="labels", dtype=Map), Field(name="tags", dtype=Array(String), tags={"milvus.max_capacity": "8"}), Field(name="counts", dtype=Array(Int64), tags={"milvus.nullable": "true"}), + Field( + name="title", + dtype=String, + tags={ + "milvus.analyzer_params": '{"tokenizer": "whitespace"}', + "milvus.enable_match": "true", + "milvus.bm25": "true", + "milvus.bm25_index_params": ( + '{"inverted_index_algo": "TAAT_NAIVE", "bm25_b": 0.3}' + ), + }, + ), ], ) rows = { 1: { "embedding": ValueProto(float_list_val=FloatList(val=[1.0, 0.0])), + "title": ValueProto(string_val="wool-blend sweater"), "brand": ValueProto(string_val="acme"), "attributes": ValueProto(json_val='{"price": 10, "color": "red"}'), "labels": python_values_to_proto_values( @@ -645,14 +658,51 @@ def test_native_complex_types_filters_and_tag_indexes( assert store.client is not None indexes = set(store.client.list_indexes(f"{project}_{fv.name}")) assert {"scalar_index_brand", "json_index_attributes_0"} <= indexes + bm25_index = store.client.describe_index(f"{project}_{fv.name}", "bm25_index_title") + assert (bm25_index["inverted_index_algo"], bm25_index["bm25_b"]) == ( + "TAAT_NAIVE", + "0.3", + ) _write_rows(store, config, fv, rows) read = _read( - store, config, fv, [1, 2], ["brand", "attributes", "labels", "tags", "counts"] + store, + config, + fv, + [1, 2], + ["brand", "attributes", "labels", "tags", "counts", "title"], ) assert read[0] == {k: v for k, v in rows[1].items() if k != "embedding"} assert read[1] is not None and read[1]["counts"].WhichOneof("val") is None + # The whitespace analyzer keeps "wool-blend" as one token. Milvus 2.6 indexes + # new rows for TEXT_MATCH a moment after the write, even with Strong consistency. + def text_match(token: str) -> List[str]: + assert store.client is not None + hits = store.client.query( + f"{project}_{fv.name}", + filter=f"TEXT_MATCH(title, '{token}')", + output_fields=["brand"], + ) + return [hit["brand"] for hit in hits] + + assert _eventually(lambda: text_match("wool-blend"), bool) == ["acme"] + assert text_match("wool") == [] + + # Milvus fills title_bm25 from the analyzed title on every write. + def bm25_search(text: str) -> List[str]: + assert store.client is not None + hits = store.client.search( + f"{project}_{fv.name}", + data=[text], + anns_field="title_bm25", + limit=2, + output_fields=["brand"], + ) + return [hit["brand"] for hit in hits[0]] + + assert _eventually(lambda: bm25_search("wool-blend"), bool) == ["acme"] + hits = store.retrieve_online_documents_v2( config, fv, diff --git a/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py b/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py index 6e32c3bc6de..360de9f6b4d 100644 --- a/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py +++ b/sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py @@ -1,5 +1,6 @@ """Unit tests for the Milvus online store, run against Milvus Lite or a mocked client.""" +import json from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Dict, List, Optional, Tuple @@ -660,6 +661,40 @@ def test_collection_and_read_consistency_levels_independent() -> None: assert all(kwargs["consistency_level"] == "Strong" for kwargs in read_calls) +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_search_names_the_vector_field_next_to_a_bm25_output( + mock_client_cls: MagicMock, +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + mock_client.describe_collection.return_value = { + "collection_name": "test_milvus_driver_embeddings", + "fields": [ + {"name": "driver_id_pk", "type": DataType.VARCHAR, "params": {}}, + {"name": "event_ts", "type": DataType.INT64, "params": {}}, + {"name": "created_ts", "type": DataType.INT64, "params": {}}, + {"name": "embedding", "type": DataType.FLOAT_VECTOR, "params": {"dim": 2}}, + {"name": "city", "type": DataType.VARCHAR, "params": {}}, + { + "name": "city_bm25", + "type": DataType.SPARSE_FLOAT_VECTOR, + "params": {}, + "is_function_output": True, + }, + ], + } + mock_client.search.return_value = [[]] + + MilvusOnlineStore().retrieve_online_documents_v2( + _mock_config(embedding_dim=2), + _vector_feature_view(), + ["city"], + embedding=[1.0, 0.0], + top_k=1, + ) + + assert mock_client.search.call_args.kwargs["anns_field"] == "embedding" + + @pytest.mark.parametrize("field", ["consistency_level", "collection_consistency_level"]) def test_invalid_consistency_level_rejected(field: str) -> None: with pytest.raises(ValidationError): @@ -1472,6 +1507,35 @@ def test_index_tags_create_scalar_and_json_path_indexes( {}, "milvus.max_capacity tag must be", ), + ( + Field(name="price", dtype=Float64, tags={"milvus.enable_match": "true"}), + {}, + "not a String feature", + ), + ( + Field(name="title", dtype=String, tags={"milvus.enable_match": "yes"}), + {}, + "must be 'true' or 'false'", + ), + ( + Field(name="title", dtype=String, tags={"milvus.analyzer_params": "[]"}), + {}, + "milvus.analyzer_params must be a JSON dict", + ), + ( + Field(name="price", dtype=Float64, tags={"milvus.bm25": "true"}), + {}, + "not a String feature", + ), + ( + Field( + name="title", + dtype=String, + tags={"milvus.bm25_index_params": '{"bm25_b": 0.3}'}, + ), + {}, + "without milvus.bm25", + ), ], ids=[ "params_without_index", @@ -1479,10 +1543,15 @@ def test_index_tags_create_scalar_and_json_path_indexes( "json_index_on_text", "vector", "capacity", + "analysis_on_non_string", + "match_not_boolean", + "analyzer_not_object", + "bm25_on_non_string", + "bm25_params_without_bm25", ], ) @patch(f"{MILVUS_MODULE}.MilvusClient") -def test_index_and_capacity_tags_are_validated( +def test_field_tags_are_validated( mock_client_cls: MagicMock, field: Field, online_store: Dict[str, Any], match: str ) -> None: mock_client = _mock_client(mock_client_cls, has_collection=False) @@ -1499,6 +1568,154 @@ def test_index_and_capacity_tags_are_validated( mock_client.create_collection.assert_not_called() +@pytest.mark.parametrize( + "tags, expected", + [ + ( + {"milvus.analyzer_params": '{"tokenizer": "whitespace"}'}, + {"enable_analyzer": True, "analyzer_params": {"tokenizer": "whitespace"}}, + ), + ( + {"milvus.enable_match": "true"}, + {"enable_analyzer": True, "enable_match": True}, + ), + ( + { + "milvus.analyzer_params": '{"tokenizer": "whitespace"}', + "milvus.enable_match": "true", + }, + { + "enable_analyzer": True, + "analyzer_params": {"tokenizer": "whitespace"}, + "enable_match": True, + }, + ), + ({"milvus.enable_match": "false"}, {}), + ], + ids=["analyzer", "match", "both", "match_false"], +) +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_text_analysis_tags_set_field_params( + mock_client_cls: MagicMock, tags: Dict[str, str], expected: Dict[str, Any] +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = FeatureView( + name="products", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="title", dtype=String, tags=tags), + ], + ) + + MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv) + + schema = mock_client.create_collection.call_args.kwargs["schema"] + params = next(field for field in schema.fields if field.name == "title").params + text_params = { + name: params[name] + for name in ("enable_analyzer", "analyzer_params", "enable_match") + if name in params + } + if "analyzer_params" in text_params: + text_params["analyzer_params"] = json.loads(text_params["analyzer_params"]) + assert text_params == expected + + +@pytest.mark.parametrize( + "tags, index_params", + [ + ({}, {}), + ( + {"milvus.bm25_index_params": '{"inverted_index_algo": "TAAT_NAIVE"}'}, + {"inverted_index_algo": "TAAT_NAIVE"}, + ), + ], + ids=["default_params", "index_params"], +) +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_bm25_tag_creates_output_function_and_index( + mock_client_cls: MagicMock, tags: Dict[str, str], index_params: Dict[str, Any] +) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = FeatureView( + name="products", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="title", dtype=String, tags={"milvus.bm25": "true", **tags}), + ], + ) + + MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv) + + schema = mock_client.create_collection.call_args.kwargs["schema"] + fields = {field.name: field for field in schema.fields} + assert fields["title"].params["enable_analyzer"] is True + assert fields["title_bm25"].dtype == DataType.SPARSE_FLOAT_VECTOR + # The sparse output is the collection's vector field, so no placeholder. + assert PLACEHOLDER_VECTOR_FIELD not in fields + [function] = schema.functions + assert (function.name, function.input_field_names, function.output_field_names) == ( + "title_bm25_fn", + ["title"], + ["title_bm25"], + ) + assert _created_indexes(mock_client)["title_bm25"] == { + "field_name": "title_bm25", + "index_type": "SPARSE_INVERTED_INDEX", + "index_name": "bm25_index_title", + "metric_type": "BM25", + **index_params, + } + + +@patch(f"{MILVUS_MODULE}.MilvusClient") +def test_bm25_output_name_clash_is_rejected(mock_client_cls: MagicMock) -> None: + mock_client = _mock_client(mock_client_cls, has_collection=False) + fv = FeatureView( + name="products", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="title", dtype=String, tags={"milvus.bm25": "true"}), + Field(name="title_bm25", dtype=String), + ], + ) + + with pytest.raises(ValueError, match="name of a milvus.bm25 output"): + MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv) + + mock_client.create_collection.assert_not_called() + + +def test_writes_leave_the_bm25_output_to_milvus(tmp_path: Path) -> None: + config = _lite_config(tmp_path) + fv = FeatureView( + name="products", + entities=[_driver_entity()], + ttl=timedelta(days=1), + schema=[ + Field(name="driver_id", dtype=Int64), + Field(name="title", dtype=String, tags={"milvus.bm25": "true"}), + ], + ) + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + _write_rows(store, config, fv, {1: {"title": ValueProto(string_val="red wool")}}) + + # A new store reads the collection's schema from Milvus, as another process would. + store = MilvusOnlineStore() + _write_rows(store, config, fv, {1: {"title": ValueProto(string_val="blue cotton")}}) + rows = _read(store, config, fv, [1], ["title"]) + + assert rows[0] is not None + assert rows[0]["title"].string_val == "blue cotton" + + @patch(f"{MILVUS_MODULE}.MilvusClient") def test_missing_tag_indexes_on_an_existing_collection_are_logged( mock_client_cls: MagicMock, caplog: pytest.LogCaptureFixture