Skip to content

Commit 32fdb65

Browse files
feat: Add BM25 field tags to the Milvus online store
milvus.bm25 on a String feature makes Feast add a sparse output, a BM25 function and its index when it creates the collection, and milvus.bm25_index_params sets that index's build parameters. Writes leave the output to Milvus, and searches name the dense vector field, which Milvus can no longer infer once the collection has a BM25 output. Co-authored-by: jonasfagerlund <jonashfagerlund@gmail.com> Signed-off-by: jonasfagerlund <jonashfagerlund@gmail.com> Signed-off-by: jiwidi <fhjaime96@gmail.com>
1 parent 69b54e2 commit 32fdb65

4 files changed

Lines changed: 284 additions & 27 deletions

File tree

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

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -358,18 +358,42 @@ Both tags apply only to `String` features and need Milvus 2.5 or later. Milvus L
358358
tags but does not apply them: its `TEXT_MATCH` works on any `String` column and always uses the
359359
standard analyzer.
360360

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.
361+
`milvus.bm25: "true"` on a `String` feature makes Milvus score it with BM25, using its analyzer
362+
(`milvus.analyzer_params`, or the standard one). It needs Milvus 2.5 or later. Feast adds a
363+
`SPARSE_FLOAT_VECTOR` field `<field>_bm25`, a BM25 function `<field>_bm25_fn` that fills it from
364+
the field's tokens, and a `SPARSE_INVERTED_INDEX` named `bm25_index_<field>`.
365+
`milvus.bm25_index_params` passes a JSON object of build parameters to that index, and requires
366+
`milvus.bm25: "true"`:
364367
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+
```python
369+
Field(
370+
name="title",
371+
dtype=String,
372+
tags={
373+
"milvus.bm25": "true",
374+
"milvus.bm25_index_params": '{"inverted_index_algo": "TAAT_NAIVE", "bm25_b": 0.3}',
375+
},
376+
),
377+
```
378+
379+
Milvus computes the `<field>_bm25` values on every write, so Feast never writes them, and they are
380+
not features to request. No feature may be named `<field>_bm25`. With `milvus.bm25`, Milvus Lite
381+
accepts only the `standard` and `jieba` tokenizers.
382+
383+
Feast itself does not query the tokens or the BM25 field: `retrieve_online_documents_v2` filters a
384+
`query_string` with `LIKE`, and Feast filters have no `TEXT_MATCH` operator. Query the collection
385+
with a Milvus client to use them.
386+
387+
The settings only apply when Feast creates a collection. Feast does not compare analyzer or match
388+
settings with an existing collection. A missing `<field>_bm25` field is reported as a
389+
[schema mismatch](#schema-mismatch), and a missing BM25 index as a missing index. To change any of
390+
them, run `feast teardown` and `feast apply`, then materialize again.
368391

369392
## Feature views without vectors
370393

371394
Milvus requires every collection to have a vector field. For feature views that have no vector
372-
feature, Feast adds a 2-dimensional `_placeholder_vector` field with a FLAT index and fills it with zeros.
395+
feature and no `milvus.bm25` field, Feast adds a 2-dimensional `_placeholder_vector` field with a
396+
FLAT index and fills it with zeros.
373397
It is never returned or searched.
374398

375399
## Functionality Matrix

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

Lines changed: 87 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
CollectionSchema,
1313
DataType,
1414
FieldSchema,
15+
Function,
16+
FunctionType,
1517
MilvusClient,
1618
)
1719
from pymilvus.client.types import LoadState
@@ -395,7 +397,9 @@ def _get_or_create_collection(
395397
use_typed = config.online_store.enable_openai_compatible_store
396398
partition_key = _partition_key_name(config.online_store, table)
397399
entity_columns = {column.name for column in table.entity_columns}
398-
scalar_indexes: List[Dict[str, Any]] = []
400+
tag_indexes: List[Dict[str, Any]] = []
401+
bm25_outputs: List[FieldSchema] = []
402+
functions: List[Function] = []
399403
for field in fields_to_add:
400404
spec = _column_spec(
401405
field,
@@ -424,10 +428,30 @@ def _get_or_create_collection(
424428
if nullable:
425429
spec["nullable"] = True
426430
spec.update(_text_analysis_params(field))
427-
scalar_indexes.extend(_scalar_index_specs(field, spec["dtype"]))
431+
tag_indexes.extend(_scalar_index_specs(field, spec["dtype"]))
428432
fields.append(FieldSchema(name=field.name, **spec))
433+
bm25 = _bm25_specs(field)
434+
if bm25 is not None:
435+
output, function, index = bm25
436+
bm25_outputs.append(output)
437+
functions.append(function)
438+
tag_indexes.append(index)
439+
# PyMilvus accepts duplicate field names, so a clash would go unnoticed.
440+
names = {f.name for f in fields}
441+
for output in bm25_outputs:
442+
if output.name in names:
443+
raise ValueError(
444+
f"Field '{output.name}' has the name of a milvus.bm25 output:"
445+
" rename it."
446+
)
447+
fields.extend(bm25_outputs)
429448
has_vector_field = any(
430-
f.dtype in (DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR)
449+
f.dtype
450+
in (
451+
DataType.FLOAT_VECTOR,
452+
DataType.BINARY_VECTOR,
453+
DataType.SPARSE_FLOAT_VECTOR,
454+
)
431455
for f in fields
432456
)
433457
if not has_vector_field:
@@ -441,7 +465,9 @@ def _get_or_create_collection(
441465
if partition_key:
442466
_mark_partition_key(fields, partition_key, table.name)
443467
schema = CollectionSchema(
444-
fields=fields, description="Feast feature view data"
468+
fields=fields,
469+
functions=functions,
470+
description="Feast feature view data",
445471
)
446472
collection_exists = self.client.has_collection(
447473
collection_name=collection_name
@@ -477,8 +503,8 @@ def _get_or_create_collection(
477503
index_type="FLAT",
478504
index_name=f"vector_index_{vector_field.name}",
479505
)
480-
for scalar_index in scalar_indexes:
481-
index_params.add_index(**scalar_index)
506+
for tag_index in tag_indexes:
507+
index_params.add_index(**tag_index)
482508
# Every collection has at least one vector field, and every
483509
# vector field is indexed, so passing the index params here
484510
# makes Milvus create the indexes and load the collection.
@@ -492,10 +518,10 @@ def _get_or_create_collection(
492518
)
493519
else:
494520
self._ensure_loaded(collection_name)
495-
_warn_if_scalar_indexes_missing(
521+
_warn_if_tag_indexes_missing(
496522
self.client,
497523
collection_name,
498-
[index["index_name"] for index in scalar_indexes],
524+
[index["index_name"] for index in tag_indexes],
499525
)
500526
description = self.client.describe_collection(collection_name)
501527
if collection_exists:
@@ -532,7 +558,13 @@ def online_write_batch(
532558
collection = self._get_or_create_collection(config, table)
533559
entity_batch_to_insert = []
534560
unique_entities: dict[str, dict[str, Any]] = {}
535-
required_fields = {field["name"] for field in collection["fields"]}
561+
# Milvus computes function outputs, such as BM25 vectors, and PyMilvus
562+
# rejects rows that carry them.
563+
required_fields = {
564+
field["name"]
565+
for field in collection["fields"]
566+
if not field.get("is_function_output")
567+
}
536568
collection_field_types = {
537569
field["name"]: field["type"] for field in collection["fields"]
538570
}
@@ -865,13 +897,16 @@ def retrieve_online_documents_v2(
865897
# Find the vector search field if we need it
866898
ann_search_field = None
867899
if embedding is not None:
868-
for field in collection["fields"]:
869-
if (
870-
field["type"] in [DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR]
871-
and field["name"] in output_fields
872-
):
873-
ann_search_field = field["name"]
874-
break
900+
vector_fields = [
901+
field["name"]
902+
for field in collection["fields"]
903+
if field["type"] in [DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR]
904+
]
905+
requested = [name for name in vector_fields if name in output_fields]
906+
# Name the only vector field even when it isn't requested: Milvus
907+
# cannot infer it once the collection also has a BM25 output.
908+
if requested or len(vector_fields) == 1:
909+
ann_search_field = (requested or vector_fields)[0]
875910

876911
if filters and filters_contain_numeric_comparison(filters):
877912
collection_field_types = {
@@ -1547,11 +1582,12 @@ def _scalar_index_specs(field: Field, dtype: DataType) -> List[Dict[str, Any]]:
15471582

15481583

15491584
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."""
1585+
"""The analyzer settings that the ``milvus.analyzer_params``,
1586+
``milvus.enable_match`` and ``milvus.bm25`` tags declare."""
15521587
analyzer_params = _json_tag(field, "milvus.analyzer_params", dict)
15531588
enable_match = _boolean_tag(field, "milvus.enable_match")
1554-
if analyzer_params is None and not enable_match:
1589+
bm25 = _boolean_tag(field, "milvus.bm25")
1590+
if analyzer_params is None and not enable_match and not bm25:
15551591
return {}
15561592
# Other types are stored as VARCHAR too, but their text is not meant to be analyzed.
15571593
if from_feast_type(field.dtype) != ValueType.STRING:
@@ -1566,7 +1602,38 @@ def _text_analysis_params(field: Field) -> Dict[str, Any]:
15661602
return params
15671603

15681604

1569-
def _warn_if_scalar_indexes_missing(
1605+
def _bm25_specs(
1606+
field: Field,
1607+
) -> Optional[Tuple[FieldSchema, Function, Dict[str, Any]]]:
1608+
"""The sparse output, BM25 function and index that the ``milvus.bm25`` tag declares."""
1609+
params = _json_tag(field, "milvus.bm25_index_params", dict)
1610+
if not _boolean_tag(field, "milvus.bm25"):
1611+
if params is not None:
1612+
raise ValueError(
1613+
f"Field '{field.name}' has a milvus.bm25_index_params tag"
1614+
" without milvus.bm25"
1615+
)
1616+
return None
1617+
output = f"{field.name}_bm25"
1618+
return (
1619+
FieldSchema(name=output, dtype=DataType.SPARSE_FLOAT_VECTOR),
1620+
Function(
1621+
name=f"{output}_fn",
1622+
input_field_names=[field.name],
1623+
output_field_names=[output],
1624+
function_type=FunctionType.BM25,
1625+
),
1626+
{
1627+
"field_name": output,
1628+
"index_type": "SPARSE_INVERTED_INDEX",
1629+
"index_name": f"bm25_index_{field.name}",
1630+
"metric_type": "BM25",
1631+
"params": params or {},
1632+
},
1633+
)
1634+
1635+
1636+
def _warn_if_tag_indexes_missing(
15701637
client: MilvusClient, collection_name: str, index_names: List[str]
15711638
) -> None:
15721639
if not index_names:

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,10 @@ def test_native_complex_types_filters_and_tag_indexes(
625625
tags={
626626
"milvus.analyzer_params": '{"tokenizer": "whitespace"}',
627627
"milvus.enable_match": "true",
628+
"milvus.bm25": "true",
629+
"milvus.bm25_index_params": (
630+
'{"inverted_index_algo": "TAAT_NAIVE", "bm25_b": 0.3}'
631+
),
628632
},
629633
),
630634
],
@@ -654,6 +658,11 @@ def test_native_complex_types_filters_and_tag_indexes(
654658
assert store.client is not None
655659
indexes = set(store.client.list_indexes(f"{project}_{fv.name}"))
656660
assert {"scalar_index_brand", "json_index_attributes_0"} <= indexes
661+
bm25_index = store.client.describe_index(f"{project}_{fv.name}", "bm25_index_title")
662+
assert (bm25_index["inverted_index_algo"], bm25_index["bm25_b"]) == (
663+
"TAAT_NAIVE",
664+
"0.3",
665+
)
657666

658667
_write_rows(store, config, fv, rows)
659668
read = _read(
@@ -680,6 +689,20 @@ def text_match(token: str) -> List[str]:
680689
assert _eventually(lambda: text_match("wool-blend"), bool) == ["acme"]
681690
assert text_match("wool") == []
682691

692+
# Milvus fills title_bm25 from the analyzed title on every write.
693+
def bm25_search(text: str) -> List[str]:
694+
assert store.client is not None
695+
hits = store.client.search(
696+
f"{project}_{fv.name}",
697+
data=[text],
698+
anns_field="title_bm25",
699+
limit=2,
700+
output_fields=["brand"],
701+
)
702+
return [hit["brand"] for hit in hits[0]]
703+
704+
assert _eventually(lambda: bm25_search("wool-blend"), bool) == ["acme"]
705+
683706
hits = store.retrieve_online_documents_v2(
684707
config,
685708
fv,

0 commit comments

Comments
 (0)