Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion docs/reference/online-stores/milvus.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<field>_bm25`, a BM25 function `<field>_bm25_fn` that fills it from
the field's tokens, and a `SPARSE_INVERTED_INDEX` named `bm25_index_<field>`.
`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 `<field>_bm25` values on every write, so Feast never writes them, and they are
not features to request. No feature may be named `<field>_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 `<field>_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
Expand Down
134 changes: 111 additions & 23 deletions sdk/python/feast/infra/online_stores/milvus_online_store/milvus.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
CollectionSchema,
DataType,
FieldSchema,
Function,
FunctionType,
MilvusClient,
)
from pymilvus.client.types import LoadState
Expand Down Expand Up @@ -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,
Expand All @@ -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 (
Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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"]
}
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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:
Expand All @@ -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"
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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,
Expand Down
Loading
Loading