Skip to content

Commit 69b54e2

Browse files
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 <jonashfagerlund@gmail.com> Signed-off-by: jonasfagerlund <jonashfagerlund@gmail.com> Signed-off-by: jiwidi <fhjaime96@gmail.com>
1 parent e81e69d commit 69b54e2

4 files changed

Lines changed: 161 additions & 8 deletions

File tree

‎docs/reference/online-stores/milvus.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,37 @@ Indexes only apply when Feast creates a collection. For an existing collection w
335335
logs a warning. To add them, run `feast teardown` and `feast apply`, then materialize again, or use
336336
the staged cutover described under [Field types](#field-types).
337337

338+
## Text analysis
339+
340+
Milvus can split a `String` feature into tokens when it stores it, so that a `TEXT_MATCH` filter
341+
finds rows by token. Declare it with field tags, and Feast sets it up when it creates the
342+
collection:
343+
344+
```python
345+
Field(
346+
name="title",
347+
dtype=String,
348+
tags={
349+
"milvus.analyzer_params": '{"tokenizer": "whitespace"}',
350+
"milvus.enable_match": "true",
351+
},
352+
),
353+
```
354+
355+
`milvus.analyzer_params` is a JSON object with the field's analyzer. Without it, Milvus uses its
356+
standard analyzer. `milvus.enable_match: "true"` builds the token index that `TEXT_MATCH` needs.
357+
Both tags apply only to `String` features and need Milvus 2.5 or later. Milvus Lite accepts both
358+
tags but does not apply them: its `TEXT_MATCH` works on any `String` column and always uses the
359+
standard analyzer.
360+
361+
Feast itself does not query the tokens: `retrieve_online_documents_v2` filters a `query_string`
362+
with `LIKE`, and Feast filters have no `TEXT_MATCH` operator. Query the collection with a Milvus
363+
client to use them.
364+
365+
The settings only apply when Feast creates a collection, and Feast does not compare them with an
366+
existing collection. To change them, run `feast teardown` and `feast apply`, then materialize
367+
again.
368+
338369
## Feature views without vectors
339370

340371
Milvus requires every collection to have a vector field. For feature views that have no vector

‎sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,7 @@ def _get_or_create_collection(
408408
f"Field '{field.name}': Array(Bool) cannot be a vector field,"
409409
" Milvus binary vectors are not supported."
410410
)
411-
nullable = _nullable_tag(field)
411+
nullable = _boolean_tag(field, "milvus.nullable")
412412
if nullable is None:
413413
nullable = spec.get("nullable", False)
414414
if nullable and (
@@ -423,6 +423,7 @@ def _get_or_create_collection(
423423
spec.pop("nullable", None)
424424
if nullable:
425425
spec["nullable"] = True
426+
spec.update(_text_analysis_params(field))
426427
scalar_indexes.extend(_scalar_index_specs(field, spec["dtype"]))
427428
fields.append(FieldSchema(name=field.name, **spec))
428429
has_vector_field = any(
@@ -1545,6 +1546,26 @@ def _scalar_index_specs(field: Field, dtype: DataType) -> List[Dict[str, Any]]:
15451546
return specs
15461547

15471548

1549+
def _text_analysis_params(field: Field) -> Dict[str, Any]:
1550+
"""The analyzer settings that the ``milvus.analyzer_params`` and
1551+
``milvus.enable_match`` tags declare."""
1552+
analyzer_params = _json_tag(field, "milvus.analyzer_params", dict)
1553+
enable_match = _boolean_tag(field, "milvus.enable_match")
1554+
if analyzer_params is None and not enable_match:
1555+
return {}
1556+
# Other types are stored as VARCHAR too, but their text is not meant to be analyzed.
1557+
if from_feast_type(field.dtype) != ValueType.STRING:
1558+
raise ValueError(
1559+
f"Field '{field.name}' has text analysis tags but is not a String feature"
1560+
)
1561+
params: Dict[str, Any] = {"enable_analyzer": True}
1562+
if analyzer_params is not None:
1563+
params["analyzer_params"] = analyzer_params
1564+
if enable_match:
1565+
params["enable_match"] = True
1566+
return params
1567+
1568+
15481569
def _warn_if_scalar_indexes_missing(
15491570
client: MilvusClient, collection_name: str, index_names: List[str]
15501571
) -> None:
@@ -1561,13 +1582,13 @@ def _warn_if_scalar_indexes_missing(
15611582
)
15621583

15631584

1564-
def _nullable_tag(field: Field) -> Optional[bool]:
1565-
if "milvus.nullable" not in field.tags:
1585+
def _boolean_tag(field: Field, tag: str) -> Optional[bool]:
1586+
if tag not in field.tags:
15661587
return None
1567-
value = field.tags["milvus.nullable"].lower()
1588+
value = field.tags[tag].lower()
15681589
if value not in ("true", "false"):
15691590
raise ValueError(
1570-
f"Field '{field.name}' has invalid milvus.nullable tag"
1571-
f" '{field.tags['milvus.nullable']}': must be 'true' or 'false'."
1591+
f"Field '{field.name}' has invalid {tag} tag"
1592+
f" '{field.tags[tag]}': must be 'true' or 'false'."
15721593
)
15731594
return value == "true"

‎sdk/python/tests/integration/online_store/test_milvus_remote.py‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -619,11 +619,20 @@ def test_native_complex_types_filters_and_tag_indexes(
619619
Field(name="labels", dtype=Map),
620620
Field(name="tags", dtype=Array(String), tags={"milvus.max_capacity": "8"}),
621621
Field(name="counts", dtype=Array(Int64), tags={"milvus.nullable": "true"}),
622+
Field(
623+
name="title",
624+
dtype=String,
625+
tags={
626+
"milvus.analyzer_params": '{"tokenizer": "whitespace"}',
627+
"milvus.enable_match": "true",
628+
},
629+
),
622630
],
623631
)
624632
rows = {
625633
1: {
626634
"embedding": ValueProto(float_list_val=FloatList(val=[1.0, 0.0])),
635+
"title": ValueProto(string_val="wool-blend sweater"),
627636
"brand": ValueProto(string_val="acme"),
628637
"attributes": ValueProto(json_val='{"price": 10, "color": "red"}'),
629638
"labels": python_values_to_proto_values(
@@ -648,11 +657,29 @@ def test_native_complex_types_filters_and_tag_indexes(
648657

649658
_write_rows(store, config, fv, rows)
650659
read = _read(
651-
store, config, fv, [1, 2], ["brand", "attributes", "labels", "tags", "counts"]
660+
store,
661+
config,
662+
fv,
663+
[1, 2],
664+
["brand", "attributes", "labels", "tags", "counts", "title"],
652665
)
653666
assert read[0] == {k: v for k, v in rows[1].items() if k != "embedding"}
654667
assert read[1] is not None and read[1]["counts"].WhichOneof("val") is None
655668

669+
# The whitespace analyzer keeps "wool-blend" as one token. Milvus 2.6 indexes
670+
# new rows for TEXT_MATCH a moment after the write, even with Strong consistency.
671+
def text_match(token: str) -> List[str]:
672+
assert store.client is not None
673+
hits = store.client.query(
674+
f"{project}_{fv.name}",
675+
filter=f"TEXT_MATCH(title, '{token}')",
676+
output_fields=["brand"],
677+
)
678+
return [hit["brand"] for hit in hits]
679+
680+
assert _eventually(lambda: text_match("wool-blend"), bool) == ["acme"]
681+
assert text_match("wool") == []
682+
656683
hits = store.retrieve_online_documents_v2(
657684
config,
658685
fv,

‎sdk/python/tests/unit/infra/online_store/test_milvus_online_store.py‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Unit tests for the Milvus online store, run against Milvus Lite or a mocked client."""
22

3+
import json
34
from datetime import datetime, timedelta, timezone
45
from pathlib import Path
56
from typing import Any, Dict, List, Optional, Tuple
@@ -1472,17 +1473,35 @@ def test_index_tags_create_scalar_and_json_path_indexes(
14721473
{},
14731474
"milvus.max_capacity tag must be",
14741475
),
1476+
(
1477+
Field(name="price", dtype=Float64, tags={"milvus.enable_match": "true"}),
1478+
{},
1479+
"not a String feature",
1480+
),
1481+
(
1482+
Field(name="title", dtype=String, tags={"milvus.enable_match": "yes"}),
1483+
{},
1484+
"must be 'true' or 'false'",
1485+
),
1486+
(
1487+
Field(name="title", dtype=String, tags={"milvus.analyzer_params": "[]"}),
1488+
{},
1489+
"milvus.analyzer_params must be a JSON dict",
1490+
),
14751491
],
14761492
ids=[
14771493
"params_without_index",
14781494
"bad_json",
14791495
"json_index_on_text",
14801496
"vector",
14811497
"capacity",
1498+
"analysis_on_non_string",
1499+
"match_not_boolean",
1500+
"analyzer_not_object",
14821501
],
14831502
)
14841503
@patch(f"{MILVUS_MODULE}.MilvusClient")
1485-
def test_index_and_capacity_tags_are_validated(
1504+
def test_field_tags_are_validated(
14861505
mock_client_cls: MagicMock, field: Field, online_store: Dict[str, Any], match: str
14871506
) -> None:
14881507
mock_client = _mock_client(mock_client_cls, has_collection=False)
@@ -1499,6 +1518,61 @@ def test_index_and_capacity_tags_are_validated(
14991518
mock_client.create_collection.assert_not_called()
15001519

15011520

1521+
@pytest.mark.parametrize(
1522+
"tags, expected",
1523+
[
1524+
(
1525+
{"milvus.analyzer_params": '{"tokenizer": "whitespace"}'},
1526+
{"enable_analyzer": True, "analyzer_params": {"tokenizer": "whitespace"}},
1527+
),
1528+
(
1529+
{"milvus.enable_match": "true"},
1530+
{"enable_analyzer": True, "enable_match": True},
1531+
),
1532+
(
1533+
{
1534+
"milvus.analyzer_params": '{"tokenizer": "whitespace"}',
1535+
"milvus.enable_match": "true",
1536+
},
1537+
{
1538+
"enable_analyzer": True,
1539+
"analyzer_params": {"tokenizer": "whitespace"},
1540+
"enable_match": True,
1541+
},
1542+
),
1543+
({"milvus.enable_match": "false"}, {}),
1544+
],
1545+
ids=["analyzer", "match", "both", "match_false"],
1546+
)
1547+
@patch(f"{MILVUS_MODULE}.MilvusClient")
1548+
def test_text_analysis_tags_set_field_params(
1549+
mock_client_cls: MagicMock, tags: Dict[str, str], expected: Dict[str, Any]
1550+
) -> None:
1551+
mock_client = _mock_client(mock_client_cls, has_collection=False)
1552+
fv = FeatureView(
1553+
name="products",
1554+
entities=[_driver_entity()],
1555+
ttl=timedelta(days=1),
1556+
schema=[
1557+
Field(name="driver_id", dtype=Int64),
1558+
Field(name="title", dtype=String, tags=tags),
1559+
],
1560+
)
1561+
1562+
MilvusOnlineStore()._get_or_create_collection(_mock_config(), fv)
1563+
1564+
schema = mock_client.create_collection.call_args.kwargs["schema"]
1565+
params = next(field for field in schema.fields if field.name == "title").params
1566+
text_params = {
1567+
name: params[name]
1568+
for name in ("enable_analyzer", "analyzer_params", "enable_match")
1569+
if name in params
1570+
}
1571+
if "analyzer_params" in text_params:
1572+
text_params["analyzer_params"] = json.loads(text_params["analyzer_params"])
1573+
assert text_params == expected
1574+
1575+
15021576
@patch(f"{MILVUS_MODULE}.MilvusClient")
15031577
def test_missing_tag_indexes_on_an_existing_collection_are_logged(
15041578
mock_client_cls: MagicMock, caplog: pytest.LogCaptureFixture

0 commit comments

Comments
 (0)