From e6d4fdb07fb0f59eed22e2092eb435a941e9cd69 Mon Sep 17 00:00:00 2001 From: jiwidi Date: Thu, 12 Nov 2026 16:18:19 +0100 Subject: [PATCH] feat: Add text analysis tags to the Milvus online store The milvus.analyzer_params and milvus.enable_match field tags set the analyzer and TEXT_MATCH on a String feature when Feast creates the collection. Feast does not query the tokens; clients that query Milvus directly can. Co-authored-by: jonasfagerlund Signed-off-by: jonasfagerlund Signed-off-by: jiwidi --- docs/reference/online-stores/milvus.md | 31 ++++++++ .../milvus_online_store/milvus.py | 33 ++++++-- .../online_store/test_milvus_remote.py | 29 ++++++- .../online_store/test_milvus_online_store.py | 76 ++++++++++++++++++- 4 files changed, 161 insertions(+), 8 deletions(-) diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index bc1561a3e3f..184d4f2d437 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -335,6 +335,37 @@ 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. + +Feast itself does not query the tokens: `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, and Feast does not compare them with an +existing collection. To change 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 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..e4c9fdd3023 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 @@ -408,7 +408,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,6 +423,7 @@ def _get_or_create_collection( spec.pop("nullable", None) if nullable: spec["nullable"] = True + spec.update(_text_analysis_params(field)) scalar_indexes.extend(_scalar_index_specs(field, spec["dtype"])) fields.append(FieldSchema(name=field.name, **spec)) has_vector_field = any( @@ -1545,6 +1546,26 @@ def _scalar_index_specs(field: Field, dtype: DataType) -> List[Dict[str, Any]]: return specs +def _text_analysis_params(field: Field) -> Dict[str, Any]: + """The analyzer settings that the ``milvus.analyzer_params`` and + ``milvus.enable_match`` tags declare.""" + analyzer_params = _json_tag(field, "milvus.analyzer_params", dict) + enable_match = _boolean_tag(field, "milvus.enable_match") + if analyzer_params is None and not enable_match: + 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 _warn_if_scalar_indexes_missing( client: MilvusClient, collection_name: str, index_names: List[str] ) -> None: @@ -1561,13 +1582,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..cb6b541d809 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,20 @@ 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", + }, + ), ], ) 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( @@ -648,11 +657,29 @@ def test_native_complex_types_filters_and_tag_indexes( _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") == [] + 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..1049af3dbc2 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 @@ -1472,6 +1473,21 @@ 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", + ), ], ids=[ "params_without_index", @@ -1479,10 +1495,13 @@ 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", ], ) @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 +1518,61 @@ 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 + + @patch(f"{MILVUS_MODULE}.MilvusClient") def test_missing_tag_indexes_on_an_existing_collection_are_logged( mock_client_cls: MagicMock, caplog: pytest.LogCaptureFixture