Unified query executor that routes based on query count and reranker type.
| 102 | |
| 103 | |
| 104 | class QueryExecutor: |
| 105 | """Unified query executor that routes based on query count and reranker type.""" |
| 106 | |
| 107 | def __init__(self, schema: CollectionSchema): |
| 108 | self._schema = schema |
| 109 | |
| 110 | def _build_queries( |
| 111 | self, ctx: QueryContext, collection: _Collection |
| 112 | ) -> list[_SearchQuery]: |
| 113 | """Build query vector list (no validation, conversion only).""" |
| 114 | if not ctx.queries: |
| 115 | return [self._build_base_search_query(ctx)] |
| 116 | return [ |
| 117 | self._build_search_query(ctx, query, collection) for query in ctx.queries |
| 118 | ] |
| 119 | |
| 120 | def execute(self, ctx: QueryContext, collection: _Collection) -> DocList: |
| 121 | """Execute a query, routing by query count. |
| 122 | |
| 123 | A single (or vector-less) query is sent to C++ as a ``_SearchQuery``; |
| 124 | multiple queries are assembled into a ``_MultiQuery``. |
| 125 | """ |
| 126 | queries = self._build_queries(ctx, collection) |
| 127 | if not queries: |
| 128 | raise ValueError("No query to execute") |
| 129 | |
| 130 | if len(queries) == 1: |
| 131 | return self._execute_single_query(queries[0], collection) |
| 132 | return self._execute_multi_query(ctx, queries, collection) |
| 133 | |
| 134 | def _execute_single_query( |
| 135 | self, query: _SearchQuery, collection: _Collection |
| 136 | ) -> DocList: |
| 137 | """Single/vector-less query: send a ``_SearchQuery`` to C++. |
| 138 | |
| 139 | Results are batch-materialized into tuples in a single C++ call |
| 140 | (the schema is resolved inside the binding from the collection), |
| 141 | avoiding per-doc Python/C++ crossings on the hot path. |
| 142 | """ |
| 143 | tuples = collection.Query(query) |
| 144 | return [Doc._from_tuple(t) if t is not None else None for t in tuples] |
| 145 | |
| 146 | def _execute_multi_query( |
| 147 | self, ctx: QueryContext, queries: list[_SearchQuery], collection: _Collection |
| 148 | ) -> DocList: |
| 149 | """Multiple queries: send a ``_MultiQuery`` to C++. |
| 150 | |
| 151 | A Python-only reranker (e.g. a model/API-based one) cannot run inside |
| 152 | the C++ MultiQuery, so each route is executed individually and merged by |
| 153 | the reranker in Python. The built-in RRF/Weighted/Callback rerankers use |
| 154 | the C++ variant-based fast path. |
| 155 | """ |
| 156 | reranker = ctx.reranker |
| 157 | if reranker is None: |
| 158 | raise ValueError( |
| 159 | "A reranker is required to merge results from multiple queries; " |
| 160 | "specify the 'reranker' argument." |
| 161 | ) |
no outgoing calls