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
27 changes: 27 additions & 0 deletions examples/query_scan_chain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Grep an existing collection with a VarChar/Text content field.

Requires a Milvus server supporting QueryScan and grep. Older servers may ignore
function_chains. The current implementation does not support count, aggregation,
GROUP BY, ORDER BY or query iterators with QueryScan.
"""

from pymilvus import MilvusClient

client = MilvusClient("http://localhost:19530")
rows = client.grep(
collection_name="source_files",
text_field="content",
args="-i -e 'timeout'",
filter="",
output_fields=["id", "path"],
limit=20,
)
for row in rows:
print(row["id"], row["path"], row["matches"])

# Each matches value is a list of matching-line objects:
# [{"content": "timeout", "line_number": 2, "line_start_offset": 8,
# "starts": [0], "ends": [7]}]
# Spans are half-open UTF-8 byte offsets within the returned line.
# Use match_field="text_hits" to customize the matching-details column name.
# Async usage: rows = await async_client.grep(...) with the same arguments.
18 changes: 18 additions & 0 deletions pymilvus/client/prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -2442,8 +2442,25 @@ def query_request(
output_fields: List[str],
partition_names: List[str],
use_default_consistency: bool = True,
function_chains: Optional[Union[FunctionChain, List[FunctionChain]]] = None,
**kwargs,
):
chains = (
[function_chains] if isinstance(function_chains, FunctionChain) else function_chains
)
if chains is None:
chains = []
if not isinstance(chains, list) or not all(isinstance(c, FunctionChain) for c in chains):
raise ParamError(
message="function_chains must be a FunctionChain or a list of FunctionChain"
)
if len(chains) > 1:
raise ParamError(message="query supports at most one QUERY_SCAN function chain")
for chain in chains:
if chain.stage != FunctionChainStage.QUERY_SCAN:
raise ParamError(message="query function chains require QUERY_SCAN stage")
if not chain.ops:
raise ParamError(message="query function chain must contain at least one op")
req = milvus_types.QueryRequest(
db_name="",
collection_name=collection_name,
Expand All @@ -2454,6 +2471,7 @@ def query_request(
use_default_consistency=use_default_consistency,
consistency_level=kwargs.get("consistency_level", 0),
expr_template_values=cls.prepare_expression_template(kwargs.get("expr_params", {})),
function_chains=[chain.to_proto() for chain in chains],
namespace=kwargs.get("namespace"),
**cls._rls_context(kwargs),
)
Expand Down
65 changes: 63 additions & 2 deletions pymilvus/function_chain/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class FunctionChainStage(IntEnum):
L1_RERANK: Runs at the second reranking stage.
L2_RERANK: Runs at the third reranking stage.
POST_PROCESS: Runs after the main query/search process.
QUERY_SCAN: Runs on query candidates before final pagination and projection.

Examples:
Create a chain for the search reranking stage::
Expand All @@ -68,6 +69,7 @@ class FunctionChainStage(IntEnum):
L1_RERANK = schema_pb2.FunctionChainStageL1Rerank
L2_RERANK = schema_pb2.FunctionChainStageL2Rerank
POST_PROCESS = schema_pb2.FunctionChainStagePostProcess
QUERY_SCAN = schema_pb2.FunctionChainStageQueryScan


@dataclass(frozen=True)
Expand Down Expand Up @@ -320,12 +322,20 @@ class FunctionChain:
proto = chain.to_proto()
"""

def __init__(self, stage: FunctionChainStage, name: str = ""):
def __init__(
self,
stage: FunctionChainStage,
name: str = "",
*,
output_columns: Optional[Sequence[str]] = None,
):
"""Create a function chain builder for the given execution stage.

Args:
stage: Execution stage where the chain should run.
name: Optional chain name.
output_columns: QueryScan columns to return alongside ordinary fields.
Exporting columns requires a non-empty chain name. Omit to filter only.
"""
try:
self._stage = FunctionChainStage(stage)
Expand All @@ -335,6 +345,55 @@ def __init__(self, stage: FunctionChainStage, name: str = ""):
raise ParamError(message="Function chain name must be a string")
self._name = name
self._ops: List[FunctionChainOp] = []
if output_columns is None:
output_columns = ()
if not isinstance(output_columns, (list, tuple)) or not all(
isinstance(column, str) and column for column in output_columns
):
raise ParamError(message="output_columns must be a list or tuple of non-empty strings")
if len(set(output_columns)) != len(output_columns):
raise ParamError(message="output_columns must be unique")
if "_original_idx" in output_columns:
raise ParamError(message="output_columns contains reserved name: _original_idx")
if output_columns and (self._stage != FunctionChainStage.QUERY_SCAN or not name):
raise ParamError(message="output_columns requires a named QUERY_SCAN function chain")
self._output_columns = tuple(output_columns)

@property
def output_columns(self) -> Sequence[str]:
"""Immutable view of columns exported into query results."""
return self._output_columns

def grep(
self, value: Union[str, ColumnRef], *, arguments: str, output: str = "matches"
) -> "FunctionChain":
"""Filter query candidates by matching a VarChar/Text field.

``arguments`` is an rg-style string, for example ``-i -e 'timeout'``.
It is forwarded unchanged; the server validates supported flags and patterns.
Export ``output`` through ``output_columns`` to return JSON matching-line
details (content, line_number, line_start_offset, starts, ends). ``line_number``
is one-based, while offsets and spans are UTF-8 byte offsets. Spans are
relative to the line; ``line_start_offset`` is relative to the input field.
Use query's limit/offset for pagination. Requires a server supporting QueryScan;
older servers may ignore function chains. The current server supports one grep
op and excludes count, aggregation, order-by and query iterators.
"""
if self._stage != FunctionChainStage.QUERY_SCAN:
raise ParamError(message="grep requires QUERY_SCAN stage")
input_name = _column_name(value, "grep input")
output_name = _column_name(output, "grep output")
Comment thread
junjiejiangjjj marked this conversation as resolved.
Resolved
if not isinstance(arguments, str):
raise ParamError(message="grep arguments must be a string")
self._ops.append(
FunctionChainOp(
op="grep",
inputs=(input_name,),
outputs=(output_name,),
params={"arguments": arguments},
)
)
return self

@property
def name(self) -> str:
Expand Down Expand Up @@ -504,6 +563,8 @@ def limit(self, limit: int, offset: int = 0) -> "FunctionChain":
return self

def to_proto(self) -> schema_pb2.FunctionChain:
proto = schema_pb2.FunctionChain(name=self._name, stage=int(self._stage))
proto = schema_pb2.FunctionChain(
name=self._name, stage=int(self._stage), output_columns=self._output_columns
)
proto.ops.extend([op.to_proto() for op in self._ops])
return proto
56 changes: 28 additions & 28 deletions pymilvus/grpc_gen/common_pb2.py

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions pymilvus/grpc_gen/common_pb2.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,8 @@ class MsgType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
ListRLSPrincipals: _ClassVar[MsgType]
DeleteRLSPrincipalTags: _ClassVar[MsgType]
GetExportSnapshotState: _ClassVar[MsgType]
ListRunningRequests: _ClassVar[MsgType]
CancelRequests: _ClassVar[MsgType]

class DslType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
__slots__ = ()
Expand Down Expand Up @@ -429,6 +431,8 @@ class ObjectPrivilege(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
PrivilegeViewRLS: _ClassVar[ObjectPrivilege]
PrivilegeManageRLS: _ClassVar[ObjectPrivilege]
PrivilegeImportBinlog: _ClassVar[ObjectPrivilege]
PrivilegeListRunningRequests: _ClassVar[ObjectPrivilege]
PrivilegeCancelRequests: _ClassVar[ObjectPrivilege]

class StateCode(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
__slots__ = ()
Expand Down Expand Up @@ -709,6 +713,8 @@ GetRLSPrincipalTags: MsgType
ListRLSPrincipals: MsgType
DeleteRLSPrincipalTags: MsgType
GetExportSnapshotState: MsgType
ListRunningRequests: MsgType
CancelRequests: MsgType
Dsl: DslType
BoolExprV1: DslType
UndefiedState: CompactionState
Expand Down Expand Up @@ -844,6 +850,8 @@ PrivilegeSkipRLS: ObjectPrivilege
PrivilegeViewRLS: ObjectPrivilege
PrivilegeManageRLS: ObjectPrivilege
PrivilegeImportBinlog: ObjectPrivilege
PrivilegeListRunningRequests: ObjectPrivilege
PrivilegeCancelRequests: ObjectPrivilege
Initializing: StateCode
Healthy: StateCode
Abnormal: StateCode
Expand Down
1,068 changes: 546 additions & 522 deletions pymilvus/grpc_gen/milvus_pb2.py

Large diffs are not rendered by default.

Loading
Loading