Skip to content
Closed
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
23 changes: 20 additions & 3 deletions pymilvus/client/field_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
"""Field-level partial-update helpers.

These helpers wrap :class:`schema_pb2.FieldPartialUpdateOp` so callers do not
need to import the generated protobuf module directly. ``FieldOp.array_append``
and ``FieldOp.array_remove`` return ready-to-use proto messages that can be
attached to a field during ``MilvusClient.upsert``.
need to import the generated protobuf module directly. ``FieldOp.array_append``,
``FieldOp.array_remove`` and ``FieldOp.path_replace`` return ready-to-use proto
messages that can be attached to a field during ``MilvusClient.upsert``.
"""

from typing import Mapping, Optional, Union
Expand Down Expand Up @@ -68,6 +68,18 @@ def array_remove() -> schema_pb2.FieldPartialUpdateOp:
"""Return an ARRAY_REMOVE op, deleting every matching element."""
return schema_pb2.FieldPartialUpdateOp(op=FieldOpType.ARRAY_REMOVE)

@staticmethod
def path_replace(path: str) -> schema_pb2.FieldPartialUpdateOp:
"""Return a PATH_REPLACE op that replaces only the value at ``path``.

``path`` is relative to the field: ``"[1]"`` selects one Array or
Array-of-Struct element, ``"[1][age]"`` one child of a struct element,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could the documented [1][age] case still be blocked by Struct operand serialization?

With a profile StructArray containing age and city, I reproduced this at the PR head through Prepare.row_upsert_param:

data = [{"id": 1, "profile": [{"age": 18}]}]
field_ops = {"profile": FieldOp.path_replace("[1][age]")}

Request preparation raises DataNotMatchException with missing required fields: {'city'}, because _validate_and_collect_struct_values still requires every schema child. Supplying city would conflict with the design requirement that a [index][child] operand contain exactly the named child.

This serializer restriction already exists on the base, but the new helper documents this use case. Do you consider this a gap that needs addressing here, with a row-upsert regression test, or is the required Struct operand support intentionally deferred?

and JSON fields use segments such as ``'["profile"][1]["age"]'``.
"""
if not isinstance(path, str) or not path:
raise ParamError(message="path_replace requires a non-empty path string")
return schema_pb2.FieldPartialUpdateOp(op=FieldOpType.PATH_REPLACE, path=path)


# Map from string alias to the concrete enum value. Kept out of the class so
# callers can extend it in the future without touching ``FieldOp``.
Expand Down Expand Up @@ -99,6 +111,11 @@ def normalize_field_ops(
resolved = _coerce_single(field_name, op)
if resolved is None or resolved.op == FieldOpType.REPLACE:
continue
if resolved.op == FieldOpType.PATH_REPLACE and not resolved.path:
raise ParamError(
message=f"PATH_REPLACE for field {field_name!r} requires a path, "
"use FieldOp.path_replace(path)"
)
normalized[field_name] = resolved
return normalized

Expand Down
2 changes: 1 addition & 1 deletion pymilvus/client/prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -1547,7 +1547,7 @@ def _apply_field_ops(
if not field_ops:
return
for field_name, op in field_ops.items():
request.field_ops.add(field_name=field_name, op=op.op)
request.field_ops.add(field_name=field_name, op=op.op, path=op.path)

@classmethod
def delete_request(
Expand Down
51 changes: 51 additions & 0 deletions tests/unit/prepare/test_partial_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,34 @@ def test_fieldop_factories_return_expected_enum_values():
assert FieldOp.array_append().op == FieldOpType.ARRAY_APPEND
assert FieldOp.array_remove().op == FieldOpType.ARRAY_REMOVE
assert FieldOp.replace().op == FieldOpType.REPLACE
op = FieldOp.path_replace("[1][age]")
assert op.op == FieldOpType.PATH_REPLACE
assert op.path == "[1][age]"


@pytest.mark.parametrize("path", ["", None, 1])
def test_fieldop_path_replace_rejects_missing_path(path):
with pytest.raises(ParamError, match="non-empty path"):
FieldOp.path_replace(path)


def test_normalize_field_ops_keeps_path_replace_path():
ops = normalize_field_ops({"profile": FieldOp.path_replace("[0]")})
assert ops["profile"].op == FieldOpType.PATH_REPLACE
assert ops["profile"].path == "[0]"


@pytest.mark.parametrize(
"op",
[
FieldOpType.PATH_REPLACE,
int(FieldOpType.PATH_REPLACE),
schema_pb2.FieldPartialUpdateOp(op=FieldOpType.PATH_REPLACE),
],
)
def test_normalize_field_ops_rejects_path_replace_without_path(op):
with pytest.raises(ParamError, match="requires a path"):
normalize_field_ops({"profile": op})


def test_normalize_field_ops_accepts_proto_message():
Expand Down Expand Up @@ -187,6 +215,20 @@ def test_batch_upsert_param_emits_field_op(array_schema):
assert op.op == FieldOpType.ARRAY_APPEND


def test_batch_upsert_param_emits_path_replace_path(array_schema):
req = Prepare.batch_upsert_param(
"test",
_batch_entities(),
"",
_fields_info(array_schema),
field_ops={"tags": FieldOp.path_replace("[0]")},
)
op = _find_field_op(req, "tags")
assert op is not None
assert op.op == FieldOpType.PATH_REPLACE
assert op.path == "[0]"


def test_batch_upsert_param_without_ops_default(array_schema):
req = Prepare.batch_upsert_param("test", _batch_entities(), "", _fields_info(array_schema))
assert req.partial_update is False
Expand All @@ -210,6 +252,15 @@ def test_apply_field_ops_appends_each_to_request():
assert byname == {"a": FieldOpType.ARRAY_APPEND, "b": FieldOpType.ARRAY_REMOVE}


def test_apply_field_ops_forwards_path():
req = milvus_pb2.UpsertRequest()
Prepare._apply_field_ops(req, {"scores": FieldOp.path_replace("[2]")})
assert len(req.field_ops) == 1
assert req.field_ops[0].field_name == "scores"
assert req.field_ops[0].op == FieldOpType.PATH_REPLACE
assert req.field_ops[0].path == "[2]"


def test_apply_field_ops_empty_is_noop():
req = milvus_pb2.UpsertRequest()
Prepare._apply_field_ops(req, {})
Expand Down
Loading