diff --git a/docs/reference/online-stores/milvus.md b/docs/reference/online-stores/milvus.md index 31169d2a8c9..731cf369b7e 100644 --- a/docs/reference/online-stores/milvus.md +++ b/docs/reference/online-stores/milvus.md @@ -99,7 +99,8 @@ online_store: | `partition_key` | unset | Field to use as the Milvus partition key in feature views that contain it. See [Partition key](#partition-key). | | `vector_enabled` | `true` | Enables vector search. | | `varchar_max_length` | `65535` | Default `max_length` of VARCHAR fields. Override per field with the `max_length` tag. | -| `enable_openai_compatible_store` | `false` | Store numeric features as native Milvus numeric types. | +| `native_numeric_types` | `false` | Store numeric and bool features as native Milvus types. See [Numeric types](#numeric-types). | +| `enable_openai_compatible_store` | `false` | Feast's cross-store flag for native numeric storage (see [vector database docs](../alpha-vector-database.md)). Same effect as `native_numeric_types`. | The full set of configuration options is available in [MilvusOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.milvus.MilvusOnlineStoreConfig). @@ -178,6 +179,35 @@ changed; Feast logs a warning for them. To add a partition key to an existing fe `feast teardown` and `feast apply`, then materialize again. {% endhint %} +## Numeric types + +By default, numeric and bool features are stored as `VARCHAR`, so range filters (`gt`, `gte`, `lt`, +`lte`) don't work on them: Milvus rejects a numeric filter value (`comparisons between VarChar and +Int64 are not supported`), and a string value compares as text (`"9" > "50"` is true). Set +`native_numeric_types: true` to store them as native Milvus `INT32`, `INT64`, `FLOAT`, `DOUBLE` +and `BOOL` fields, which compare numerically. `enable_openai_compatible_store: true` has the same +effect. + +The setting only applies when Feast creates a collection. Feast detects the storage type of each +existing collection, so reads and writes keep working whichever way the collection was created, +and Feast logs a warning when numeric range filters are used on a `VARCHAR` collection. + +To migrate an existing feature view, set `native_numeric_types: true` and recreate its collection +in one of these ways: + +* **Teardown and reload.** Run `feast teardown` and `feast apply`, then materialize again. +* **Staged cutover.** Add a copy of the feature view under a new name and run `feast apply`, which + creates a new collection with native types. Materialize it, move readers to the new name, then + remove the old feature view and run `feast apply` again to drop its collection. + +{% hint style="warning" %} +`feast teardown` drops the collections of every feature view in the project, not just the one you +are migrating. Online reads fail until materialization finishes, and rows that only exist in the +online store, such as those written by push sources or `write_to_online_store`, are lost. For +production, use the staged cutover, or back up the collections first with +[Milvus Backup](https://milvus.io/docs/milvus_backup_overview.md). +{% endhint %} + ## Consistency level By default Milvus uses `Bounded` consistency, so a read issued straight after materialization may 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 722d8a6ec7b..d60e9513fd0 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 @@ -246,6 +246,10 @@ class MilvusOnlineStoreConfig(FeastConfigBaseModel, VectorStoreConfig): username: Optional[StrictStr] = "" password: Optional[StrictStr] = "" enable_openai_compatible_store: Optional[bool] = False + # Store numeric and bool features as native Milvus types instead of VARCHAR, + # so range filters compare numerically. Also enabled by + # enable_openai_compatible_store. Only applies to new collections. + native_numeric_types: Optional[bool] = False varchar_max_length: Optional[int] = 65535 @field_validator("varchar_max_length") @@ -333,7 +337,7 @@ def _get_or_create_collection( "created_timestamp", ] fields_to_add = [f for f in table.schema if f.name not in fields_to_exclude] - use_typed = config.online_store.enable_openai_compatible_store + use_typed = _use_native_numeric_types(config.online_store) for field in fields_to_add: dtype = FEAST_PRIMITIVE_TO_MILVUS_TYPE_MAPPING.get(field.dtype) if dtype is None and isinstance(field.dtype, ComplexFeastType): @@ -827,12 +831,12 @@ def retrieve_online_documents_v2( if not has_native: logger.warning( "Numeric comparison filters (gt, gte, lt, lte) are being used " - "but this collection stores numeric fields as VARCHAR. This " - "causes lexicographic comparison instead of numeric comparison " - "(e.g. '9' > '100' is True as a string). To fix this, set " - "'enable_openai_compatible_store: true' in your online_store " - "config, then teardown and re-apply your feature store to " - "recreate collections with native numeric types." + "but this collection stores numeric fields as VARCHAR. Milvus " + "rejects numeric filter values on VARCHAR fields, and string " + "values compare lexicographically (e.g. '9' > '50' is True). " + "To fix this, set 'native_numeric_types: true' in your " + "online_store config and recreate the collection; see the " + "Milvus online store docs for migration options." ) metadata_filter_expr = MilvusFilterTranslator().translate(filters) @@ -1057,6 +1061,13 @@ def _table_id(project: str, table: FeatureView, enable_versioning: bool = False) return compute_table_id(project, table, enable_versioning) +def _use_native_numeric_types(online_config: MilvusOnlineStoreConfig) -> bool: + return bool( + online_config.native_numeric_types + or online_config.enable_openai_compatible_store + ) + + def _is_autoindex(online_config: MilvusOnlineStoreConfig) -> bool: return (online_config.index_type or "").upper() == "AUTOINDEX" 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 d5e227c8b68..d009cf577bb 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 @@ -7,7 +7,7 @@ import pytest from pydantic import ValidationError -from pymilvus import DataType, MilvusClient +from pymilvus import DataType, MilvusClient, MilvusException from pymilvus.client.types import LoadState from feast import Entity, FeatureView @@ -746,3 +746,105 @@ def test_warns_when_existing_collection_lacks_partition_key( assert "created without partition key 'brand_id'" in caplog.text mock_client.create_collection.assert_not_called() + + +@pytest.mark.parametrize( + "online_store, expected_type", + [ + ({}, DataType.VARCHAR), + ({"native_numeric_types": True}, DataType.FLOAT), + ({"enable_openai_compatible_store": True}, DataType.FLOAT), + ], +) +def test_native_numeric_types( + tmp_path: Path, online_store: Dict[str, Any], expected_type: DataType +) -> None: + config = _lite_config(tmp_path, **online_store) + fv = _catalog_feature_view() + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + + assert store.client is not None + fields = store.client.describe_collection("test_milvus_products")["fields"] + assert {f["name"]: f["type"] for f in fields}["price"] == expected_type + + +def _write_priced_products( + store: MilvusOnlineStore, config: RepoConfig, fv: FeatureView +) -> None: + embedding = ValueProto() + embedding.float_list_val.val.extend([1.0, 0.0]) + now = datetime.now(timezone.utc) + store.online_write_batch( + config, + fv, + [ + ( + _product_key(product_id), + { + "brand_id": ValueProto(string_val="acme"), + "embedding": embedding, + "title": ValueProto(string_val=title), + "price": ValueProto(float_val=price), + }, + now, + now, + ) + for product_id, title, price in [(1, "cheap", 9.0), (2, "pricey", 100.0)] + ], + progress=None, + ) + + +def _titles_priced_above( + store: MilvusOnlineStore, config: RepoConfig, fv: FeatureView, value: Any +) -> List[str]: + results = store.retrieve_online_documents_v2( + config, + fv, + ["embedding", "title", "price"], + embedding=[1.0, 0.0], + top_k=5, + distance_metric="COSINE", + filters=ComparisonFilter(type="gt", key="price", value=value), + ) + return [values["title"].string_val for _, _, values in results if values] + + +def test_native_numeric_range_filter_and_round_trip(tmp_path: Path) -> None: + config = _lite_config(tmp_path, native_numeric_types=True) + fv = _catalog_feature_view() + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + _write_priced_products(store, config, fv) + + # As strings, "9.0" > "50" would be true; natively only 100.0 matches. + assert _titles_priced_above(store, config, fv, 50) == ["pricey"] + + rows = store.online_read(config, fv, [_product_key(1)], ["price", "title"]) + assert rows[0][1] is not None and rows[0][1]["price"].float_val == 9.0 + + +def test_native_numeric_types_keeps_existing_varchar_collection( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + fv = _catalog_feature_view() + MilvusOnlineStore().update(_lite_config(tmp_path), [], [fv], [], [], partial=False) + + # Turn the setting on without a teardown: the collection stays VARCHAR. + config = _lite_config(tmp_path, native_numeric_types=True) + store = MilvusOnlineStore() + store.update(config, [], [fv], [], [], partial=False) + assert store.client is not None + fields = store.client.describe_collection("test_milvus_products")["fields"] + assert {f["name"]: f["type"] for f in fields}["price"] == DataType.VARCHAR + + _write_priced_products(store, config, fv) + rows = store.online_read(config, fv, [_product_key(1)], ["price", "title"]) + assert rows[0][1] is not None and rows[0][1]["price"].float_val == 9.0 + + # Milvus rejects numeric values on VARCHAR fields; strings compare as text. + with pytest.raises(MilvusException): + _titles_priced_above(store, config, fv, 50) + assert "stores numeric fields as VARCHAR" in caplog.text + assert _titles_priced_above(store, config, fv, "50") == ["cheap"]