|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. |
| 2 | +# All rights reserved. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +"""Translate root query filter options into LanceDB's native ``where`` predicate. |
| 6 | +
|
| 7 | +LanceDB owns predicate execution. This module only maps stable root query |
| 8 | +options such as source and page filters onto the table columns used by both |
| 9 | +older local indexes and the VectorDB service, where ``metadata`` and ``source`` |
| 10 | +are JSON strings at rest. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import json |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +from nemo_retriever.query.options import QueryFilterOptions |
| 19 | + |
| 20 | + |
| 21 | +def _clean_str(value: str | None) -> str | None: |
| 22 | + cleaned = (value or "").strip() |
| 23 | + return cleaned or None |
| 24 | + |
| 25 | + |
| 26 | +def _sql_string(value: str) -> str: |
| 27 | + return "'" + value.replace("'", "''") + "'" |
| 28 | + |
| 29 | + |
| 30 | +def _like_clause(column: str, pattern: str, *, escape: bool = False) -> str: |
| 31 | + clause = f"{column} LIKE {_sql_string(pattern)}" |
| 32 | + if escape: |
| 33 | + clause += " ESCAPE '\\'" |
| 34 | + return clause |
| 35 | + |
| 36 | + |
| 37 | +def _like_pattern_literal(value: str) -> str: |
| 38 | + return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") |
| 39 | + |
| 40 | + |
| 41 | +def _json_member_patterns(key: str, value: str) -> list[str]: |
| 42 | + encoded_value = _like_pattern_literal(json.dumps(value, ensure_ascii=False)) |
| 43 | + return [ |
| 44 | + f'%"{key}":{encoded_value}%', |
| 45 | + f'%"{key}": {encoded_value}%', |
| 46 | + ] |
| 47 | + |
| 48 | + |
| 49 | +def _source_json_member_clause(key: str, value: str) -> str: |
| 50 | + return " OR ".join(_like_clause("source", pattern, escape=True) for pattern in _json_member_patterns(key, value)) |
| 51 | + |
| 52 | + |
| 53 | +def _source_id_clause(source_id: str) -> str: |
| 54 | + clauses = [ |
| 55 | + _source_json_member_clause("source_id", source_id), |
| 56 | + f"source = {_sql_string(source_id)}", |
| 57 | + ] |
| 58 | + return "(" + " OR ".join(clauses) + ")" |
| 59 | + |
| 60 | + |
| 61 | +def _source_clause(source: str) -> str: |
| 62 | + clauses = [ |
| 63 | + _source_json_member_clause("source_id", source), |
| 64 | + _source_json_member_clause("source_name", source), |
| 65 | + f"source = {_sql_string(source)}", |
| 66 | + ] |
| 67 | + return "(" + " OR ".join(clauses) + ")" |
| 68 | + |
| 69 | + |
| 70 | +def _page_number_clause(page_number: int) -> str: |
| 71 | + page = int(page_number) |
| 72 | + if page < 0: |
| 73 | + raise ValueError("page_number must be greater than or equal to 0.") |
| 74 | + patterns = [ |
| 75 | + f'%"page_number":{page},%', |
| 76 | + f'%"page_number":{page}}}%', |
| 77 | + f'%"page_number": {page},%', |
| 78 | + f'%"page_number": {page}}}%', |
| 79 | + f'%"page_number":"{page}"%', |
| 80 | + f'%"page_number": "{page}"%', |
| 81 | + ] |
| 82 | + return "(" + " OR ".join(_like_clause("metadata", pattern) for pattern in patterns) + ")" |
| 83 | + |
| 84 | + |
| 85 | +def build_query_where_clause(options: QueryFilterOptions) -> str | None: |
| 86 | + """Build the LanceDB predicate for root query filters.""" |
| 87 | + clauses: list[str] = [] |
| 88 | + |
| 89 | + source_id = _clean_str(options.source_id) |
| 90 | + if source_id is not None: |
| 91 | + clauses.append(_source_id_clause(source_id)) |
| 92 | + |
| 93 | + source = _clean_str(options.source) |
| 94 | + if source is not None: |
| 95 | + clauses.append(_source_clause(source)) |
| 96 | + |
| 97 | + if options.page_number is not None: |
| 98 | + clauses.append(_page_number_clause(options.page_number)) |
| 99 | + |
| 100 | + where = _clean_str(options.where) |
| 101 | + if where is not None: |
| 102 | + clauses.append(where if not clauses else f"({where})") |
| 103 | + |
| 104 | + if not clauses: |
| 105 | + return None |
| 106 | + return " AND ".join(clauses) |
| 107 | + |
| 108 | + |
| 109 | +def query_filter_payload(options: QueryFilterOptions) -> dict[str, Any]: |
| 110 | + """Return the public service query filter payload for non-empty fields.""" |
| 111 | + payload: dict[str, Any] = {} |
| 112 | + |
| 113 | + source_id = _clean_str(options.source_id) |
| 114 | + if source_id is not None: |
| 115 | + payload["source_id"] = source_id |
| 116 | + |
| 117 | + source = _clean_str(options.source) |
| 118 | + if source is not None: |
| 119 | + payload["source"] = source |
| 120 | + |
| 121 | + if options.page_number is not None: |
| 122 | + page_number = int(options.page_number) |
| 123 | + if page_number < 0: |
| 124 | + raise ValueError("page_number must be greater than or equal to 0.") |
| 125 | + payload["page_number"] = page_number |
| 126 | + |
| 127 | + where = _clean_str(options.where) |
| 128 | + if where is not None: |
| 129 | + payload["where"] = where |
| 130 | + |
| 131 | + return payload |
0 commit comments