orchestrator-core 4.5.0a2__py3-none-any.whl → 4.5.0a3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. orchestrator/__init__.py +1 -1
  2. orchestrator/api/api_v1/endpoints/search.py +13 -0
  3. orchestrator/devtools/populator.py +16 -0
  4. orchestrator/log_config.py +1 -0
  5. orchestrator/migrations/helpers.py +1 -1
  6. orchestrator/schemas/search.py +13 -0
  7. orchestrator/schemas/workflow.py +1 -0
  8. orchestrator/search/agent/__init__.py +13 -0
  9. orchestrator/search/agent/agent.py +13 -0
  10. orchestrator/search/agent/prompts.py +13 -0
  11. orchestrator/search/agent/state.py +13 -0
  12. orchestrator/search/agent/tools.py +27 -5
  13. orchestrator/search/core/__init__.py +12 -0
  14. orchestrator/search/core/embedding.py +13 -4
  15. orchestrator/search/core/exceptions.py +14 -0
  16. orchestrator/search/core/types.py +15 -0
  17. orchestrator/search/core/validators.py +13 -0
  18. orchestrator/search/filters/__init__.py +13 -0
  19. orchestrator/search/filters/base.py +23 -18
  20. orchestrator/search/filters/date_filters.py +13 -0
  21. orchestrator/search/filters/definitions.py +16 -2
  22. orchestrator/search/filters/ltree_filters.py +16 -3
  23. orchestrator/search/filters/numeric_filter.py +13 -0
  24. orchestrator/search/indexing/__init__.py +13 -0
  25. orchestrator/search/indexing/indexer.py +13 -0
  26. orchestrator/search/indexing/registry.py +13 -0
  27. orchestrator/search/indexing/tasks.py +13 -0
  28. orchestrator/search/indexing/traverse.py +17 -5
  29. orchestrator/search/retrieval/__init__.py +13 -0
  30. orchestrator/search/retrieval/builder.py +17 -7
  31. orchestrator/search/retrieval/engine.py +35 -29
  32. orchestrator/search/retrieval/exceptions.py +90 -0
  33. orchestrator/search/retrieval/pagination.py +13 -0
  34. orchestrator/search/retrieval/retrievers/__init__.py +26 -0
  35. orchestrator/search/retrieval/retrievers/base.py +122 -0
  36. orchestrator/search/retrieval/retrievers/fuzzy.py +94 -0
  37. orchestrator/search/retrieval/retrievers/hybrid.py +188 -0
  38. orchestrator/search/retrieval/retrievers/semantic.py +94 -0
  39. orchestrator/search/retrieval/retrievers/structured.py +39 -0
  40. orchestrator/search/retrieval/utils.py +21 -7
  41. orchestrator/search/retrieval/validation.py +54 -76
  42. orchestrator/search/schemas/__init__.py +12 -0
  43. orchestrator/search/schemas/parameters.py +13 -0
  44. orchestrator/search/schemas/results.py +14 -1
  45. orchestrator/workflows/tasks/validate_products.py +1 -1
  46. {orchestrator_core-4.5.0a2.dist-info → orchestrator_core-4.5.0a3.dist-info}/METADATA +2 -2
  47. {orchestrator_core-4.5.0a2.dist-info → orchestrator_core-4.5.0a3.dist-info}/RECORD +49 -43
  48. orchestrator/search/retrieval/retriever.py +0 -447
  49. {orchestrator_core-4.5.0a2.dist-info → orchestrator_core-4.5.0a3.dist-info}/WHEEL +0 -0
  50. {orchestrator_core-4.5.0a2.dist-info → orchestrator_core-4.5.0a3.dist-info}/licenses/LICENSE +0 -0
@@ -1,3 +1,16 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
1
14
  import re
2
15
  from abc import ABC, abstractmethod
3
16
  from collections.abc import Iterable
@@ -19,7 +32,7 @@ from orchestrator.domain.lifecycle import (
19
32
  from orchestrator.schemas.process import ProcessSchema
20
33
  from orchestrator.schemas.workflow import WorkflowSchema
21
34
  from orchestrator.search.core.exceptions import ModelLoadError, ProductNotInRegistryError
22
- from orchestrator.search.core.types import ExtractedField, FieldType
35
+ from orchestrator.search.core.types import LTREE_SEPARATOR, ExtractedField, FieldType
23
36
  from orchestrator.types import SubscriptionLifecycle
24
37
 
25
38
  logger = structlog.get_logger(__name__)
@@ -30,7 +43,6 @@ DatabaseEntity = SubscriptionTable | ProductTable | ProcessTable | WorkflowTable
30
43
  class BaseTraverser(ABC):
31
44
  """Base class for traversing database models and extracting searchable fields."""
32
45
 
33
- _LTREE_SEPARATOR = "."
34
46
  _MAX_DEPTH = 40
35
47
 
36
48
  @classmethod
@@ -62,7 +74,7 @@ class BaseTraverser(ABC):
62
74
  except Exception as e:
63
75
  logger.error(f"Failed to access field '{name}' on {model_class.__name__}", error=str(e))
64
76
  continue
65
- new_path = f"{path}{cls._LTREE_SEPARATOR}{name}" if path else name
77
+ new_path = f"{path}{LTREE_SEPARATOR}{name}" if path else name
66
78
  annotation = field.annotation if hasattr(field, "annotation") else field.return_type
67
79
  yield from cls._yield_fields_for_value(value, new_path, annotation)
68
80
 
@@ -197,7 +209,7 @@ class ProductTraverser(BaseTraverser):
197
209
  fields = []
198
210
 
199
211
  # Add the block itself as a BLOCK type
200
- block_name = block_path.split(cls._LTREE_SEPARATOR)[-1]
212
+ block_name = block_path.split(LTREE_SEPARATOR)[-1]
201
213
  fields.append(ExtractedField(path=block_path, value=block_name, value_type=FieldType.BLOCK))
202
214
 
203
215
  # Extract all field names from the block as RESOURCE_TYPE
@@ -223,7 +235,7 @@ class ProductTraverser(BaseTraverser):
223
235
  ExtractedField(path=field_path, value=field_name, value_type=FieldType.RESOURCE_TYPE)
224
236
  )
225
237
  # And potentially traverse the first item for schema
226
- first_item_path = f"{field_path}{cls._LTREE_SEPARATOR}0"
238
+ first_item_path = f"{field_path}{LTREE_SEPARATOR}0"
227
239
  nested_fields = cls._extract_block_schema(field_value[0], first_item_path)
228
240
  fields.extend(nested_fields)
229
241
  else:
@@ -1,3 +1,16 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
1
14
  from .engine import execute_search
2
15
 
3
16
  __all__ = ["execute_search"]
@@ -1,3 +1,16 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
1
14
  from collections import defaultdict
2
15
  from typing import Sequence
3
16
 
@@ -23,16 +36,13 @@ def build_candidate_query(params: BaseSearchParameters) -> Select:
23
36
  from the index table for the given entity type, applying any structured
24
37
  filters from the provided search parameters.
25
38
 
26
- Parameters
27
- ----------
28
- params : BaseSearchParameters
29
- The search parameters containing the entity type and optional filters.
39
+ Args:
40
+ params (BaseSearchParameters): The search parameters containing the entity type and optional filters.
30
41
 
31
42
  Returns:
32
- -------
33
- Select
34
- The SQLAlchemy `Select` object representing the query.
43
+ Select: The SQLAlchemy `Select` object representing the query.
35
44
  """
45
+
36
46
  stmt = select(AiSearchIndex.entity_id).where(AiSearchIndex.entity_type == params.entity_type.value).distinct()
37
47
 
38
48
  if params.filters is not None:
@@ -1,3 +1,16 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
1
14
  from collections.abc import Sequence
2
15
 
3
16
  import structlog
@@ -11,7 +24,7 @@ from orchestrator.search.schemas.results import MatchingField, SearchResponse, S
11
24
 
12
25
  from .builder import build_candidate_query
13
26
  from .pagination import PaginationParams
14
- from .retriever import Retriever
27
+ from .retrievers import Retriever
15
28
  from .utils import generate_highlight_indices
16
29
 
17
30
  logger = structlog.get_logger(__name__)
@@ -25,16 +38,14 @@ def _format_response(
25
38
  Converts raw SQLAlchemy `RowMapping` objects into `SearchResult` instances,
26
39
  including highlight metadata if present in the database results.
27
40
 
28
- Parameters
29
- ----------
30
- db_rows : Sequence[RowMapping]
31
- The rows returned from the executed SQLAlchemy query.
41
+ Args:
42
+ db_rows (Sequence[RowMapping]): The rows returned from the executed SQLAlchemy query.
43
+ search_params (BaseSearchParameters): The search parameters, including query text and filters.
44
+ metadata (SearchMetadata): Metadata about the search execution.
32
45
 
33
46
  Returns:
34
- -------
35
- SearchResponse
36
- A list of `SearchResult` objects containing entity IDs, scores, and
37
- optional highlight information.
47
+ SearchResponse: A list of `SearchResult` objects containing entity IDs, scores,
48
+ and optional highlight information.
38
49
  """
39
50
 
40
51
  if not db_rows:
@@ -46,11 +57,11 @@ def _format_response(
46
57
  for row in db_rows:
47
58
  matching_field = None
48
59
 
49
- if user_query and row.get("highlight_text") and row.get("highlight_path"):
50
- # Text/semantic searches
51
- text = row.highlight_text
52
- path = row.highlight_path
53
-
60
+ if (
61
+ user_query
62
+ and (text := row.get(Retriever.HIGHLIGHT_TEXT_LABEL))
63
+ and (path := row.get(Retriever.HIGHLIGHT_PATH_LABEL))
64
+ ):
54
65
  if not isinstance(text, str):
55
66
  text = str(text)
56
67
  if not isinstance(path, str):
@@ -114,26 +125,21 @@ async def execute_search(
114
125
  applies the appropriate ranking strategy, and executes the final ranked
115
126
  query to retrieve results.
116
127
 
117
- Parameters
118
- ----------
119
- search_params : BaseSearchParameters
120
- The search parameters specifying vector, fuzzy, or filter criteria.
121
- db_session : Session
122
- The active SQLAlchemy session for executing the query.
123
- limit : int, optional
124
- The maximum number of search results to return, by default 5.
128
+ Args:
129
+ search_params (BaseSearchParameters): The search parameters specifying vector, fuzzy, or filter criteria.
130
+ db_session (Session): The active SQLAlchemy session for executing the query.
131
+ pagination_params (PaginationParams): Parameters controlling pagination of the search results.
132
+ limit (int, optional): The maximum number of search results to return, by default 5.
125
133
 
126
134
  Returns:
127
- -------
128
- SearchResponse
129
- A list of `SearchResult` objects containing entity IDs, scores, and
130
- optional highlight metadata.
135
+ SearchResponse: A list of `SearchResult` objects containing entity IDs, scores,
136
+ and optional highlight metadata.
131
137
 
132
138
  Notes:
133
- -----
134
- If no vector query, filters, or fuzzy term are provided, a warning is logged
135
- and an empty result set is returned.
139
+ If no vector query, filters, or fuzzy term are provided, a warning is logged
140
+ and an empty result set is returned.
136
141
  """
142
+
137
143
  if not search_params.vector_query and not search_params.filters and not search_params.fuzzy_term:
138
144
  logger.warning("No search criteria provided (vector_query, fuzzy_term, or filters).")
139
145
  return SearchResponse(results=[], metadata=SearchMetadata.empty())
@@ -0,0 +1,90 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
14
+ from orchestrator.search.core.types import FilterOp
15
+
16
+
17
+ class FilterValidationError(Exception):
18
+ """Base exception for filter validation errors."""
19
+
20
+ pass
21
+
22
+
23
+ class InvalidLtreePatternError(FilterValidationError):
24
+ """Raised when an ltree pattern has invalid ltree query syntax."""
25
+
26
+ def __init__(self, pattern: str) -> None:
27
+ message = f"Ltree pattern '{pattern}' has invalid syntax. Use valid PostgreSQL ltree lquery syntax."
28
+ super().__init__(message)
29
+
30
+
31
+ class EmptyFilterPathError(FilterValidationError):
32
+ """Raised when a filter path is empty or contains only whitespace."""
33
+
34
+ def __init__(self) -> None:
35
+ message = (
36
+ "Filter path cannot be empty. Provide a valid path like 'subscription.product.name' or 'workflow.name'."
37
+ )
38
+ super().__init__(message)
39
+
40
+
41
+ class PathNotFoundError(FilterValidationError):
42
+ """Raised when a filter path doesn't exist in the database schema.
43
+
44
+ Examples:
45
+ Using a non-existent filter path:
46
+
47
+ >>> print(PathNotFoundError('subscription.nonexistent.field'))
48
+ Path 'subscription.nonexistent.field' does not exist in the database.
49
+ """
50
+
51
+ def __init__(self, path: str) -> None:
52
+ message = f"Path '{path}' does not exist in the database."
53
+ super().__init__(message)
54
+
55
+
56
+ class IncompatibleFilterTypeError(FilterValidationError):
57
+ """Raised when a filter operator is incompatible with the field's data type.
58
+
59
+ Examples:
60
+ Using a numeric comparison operator on a string field:
61
+
62
+ >>> print(IncompatibleFilterTypeError(
63
+ ... operator='gt',
64
+ ... field_type='string',
65
+ ... path='subscription.customer_name',
66
+ ... expected_operators=[FilterOp.EQ, FilterOp.NEQ, FilterOp.LIKE],
67
+ ... ))
68
+ Operator 'gt' is not compatible with field type 'string' for path 'subscription.customer_name'. Valid operators for 'string': [eq, neq, like]
69
+ """
70
+
71
+ def __init__(self, operator: str, field_type: str, path: str, expected_operators: list[FilterOp]) -> None:
72
+ valid_ops_str = ", ".join([op.value for op in expected_operators])
73
+ message = f"Operator '{operator}' is not compatible with field type '{field_type}' for path '{path}'. Valid operators for '{field_type}': [{valid_ops_str}]"
74
+
75
+ super().__init__(message)
76
+
77
+
78
+ class InvalidEntityPrefixError(FilterValidationError):
79
+ """Raised when a filter path doesn't have the correct entity type prefix.
80
+
81
+ Examples:
82
+ Using wrong entity prefix in filter path:
83
+
84
+ >>> print(InvalidEntityPrefixError('workflow.name', 'subscription.', 'SUBSCRIPTION'))
85
+ Filter path 'workflow.name' must start with 'subscription.' for SUBSCRIPTION searches, or use '*' for wildcard paths.
86
+ """
87
+
88
+ def __init__(self, path: str, expected_prefix: str, entity_type: str) -> None:
89
+ message = f"Filter path '{path}' must start with '{expected_prefix}' for {entity_type} searches, or use '*' for wildcard paths."
90
+ super().__init__(message)
@@ -1,3 +1,16 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
1
14
  import array
2
15
  import base64
3
16
  from dataclasses import dataclass
@@ -0,0 +1,26 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
14
+ from .base import Retriever
15
+ from .fuzzy import FuzzyRetriever
16
+ from .hybrid import RrfHybridRetriever
17
+ from .semantic import SemanticRetriever
18
+ from .structured import StructuredRetriever
19
+
20
+ __all__ = [
21
+ "Retriever",
22
+ "FuzzyRetriever",
23
+ "RrfHybridRetriever",
24
+ "SemanticRetriever",
25
+ "StructuredRetriever",
26
+ ]
@@ -0,0 +1,122 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
14
+ from abc import ABC, abstractmethod
15
+ from decimal import Decimal
16
+
17
+ import structlog
18
+ from sqlalchemy import BindParameter, Numeric, Select, literal
19
+
20
+ from orchestrator.search.core.types import FieldType, SearchMetadata
21
+ from orchestrator.search.schemas.parameters import BaseSearchParameters
22
+
23
+ from ..pagination import PaginationParams
24
+
25
+ logger = structlog.get_logger(__name__)
26
+
27
+
28
+ class Retriever(ABC):
29
+ """Abstract base class for applying a ranking strategy to a search query."""
30
+
31
+ SCORE_PRECISION = 12
32
+ SCORE_NUMERIC_TYPE = Numeric(38, 12)
33
+ HIGHLIGHT_TEXT_LABEL = "highlight_text"
34
+ HIGHLIGHT_PATH_LABEL = "highlight_path"
35
+ SCORE_LABEL = "score"
36
+ SEARCHABLE_FIELD_TYPES = [
37
+ FieldType.STRING.value,
38
+ FieldType.UUID.value,
39
+ FieldType.BLOCK.value,
40
+ FieldType.RESOURCE_TYPE.value,
41
+ ]
42
+
43
+ @classmethod
44
+ async def from_params(
45
+ cls,
46
+ params: BaseSearchParameters,
47
+ pagination_params: PaginationParams,
48
+ ) -> "Retriever":
49
+ """Create the appropriate retriever instance from search parameters.
50
+
51
+ Args:
52
+ params (BaseSearchParameters): Search parameters including vector queries, fuzzy terms, and filters.
53
+ pagination_params (PaginationParams): Pagination parameters for cursor-based paging.
54
+
55
+ Returns:
56
+ Retriever: A concrete retriever instance (semantic, fuzzy, hybrid, or structured).
57
+ """
58
+
59
+ from .fuzzy import FuzzyRetriever
60
+ from .hybrid import RrfHybridRetriever
61
+ from .semantic import SemanticRetriever
62
+ from .structured import StructuredRetriever
63
+
64
+ fuzzy_term = params.fuzzy_term
65
+ q_vec = await cls._get_query_vector(params.vector_query, pagination_params.q_vec_override)
66
+
67
+ # If semantic search was attempted but failed, fall back to fuzzy with the full query
68
+ fallback_fuzzy_term = fuzzy_term
69
+ if q_vec is None and params.vector_query is not None and params.query is not None:
70
+ fallback_fuzzy_term = params.query
71
+
72
+ if q_vec is not None and fallback_fuzzy_term is not None:
73
+ return RrfHybridRetriever(q_vec, fallback_fuzzy_term, pagination_params)
74
+ if q_vec is not None:
75
+ return SemanticRetriever(q_vec, pagination_params)
76
+ if fallback_fuzzy_term is not None:
77
+ return FuzzyRetriever(fallback_fuzzy_term, pagination_params)
78
+
79
+ return StructuredRetriever(pagination_params)
80
+
81
+ @classmethod
82
+ async def _get_query_vector(
83
+ cls, vector_query: str | None, q_vec_override: list[float] | None
84
+ ) -> list[float] | None:
85
+ """Get query vector either from override or by generating from text."""
86
+ if q_vec_override:
87
+ return q_vec_override
88
+
89
+ if not vector_query:
90
+ return None
91
+
92
+ from orchestrator.search.core.embedding import QueryEmbedder
93
+
94
+ q_vec = await QueryEmbedder.generate_for_text_async(vector_query)
95
+ if not q_vec:
96
+ logger.warning("Embedding generation failed; using non-semantic retriever")
97
+ return None
98
+
99
+ return q_vec
100
+
101
+ @abstractmethod
102
+ def apply(self, candidate_query: Select) -> Select:
103
+ """Apply the ranking logic to the given candidate query.
104
+
105
+ Args:
106
+ candidate_query (Select): A SQLAlchemy `Select` statement returning candidate entity IDs.
107
+
108
+ Returns:
109
+ Select: A new `Select` statement with ranking expressions applied.
110
+ """
111
+ ...
112
+
113
+ def _quantize_score_for_pagination(self, score_value: float) -> BindParameter[Decimal]:
114
+ """Convert score value to properly quantized Decimal parameter for pagination."""
115
+ pas_dec = Decimal(str(score_value)).quantize(Decimal("0.000000000001"))
116
+ return literal(pas_dec, type_=self.SCORE_NUMERIC_TYPE)
117
+
118
+ @property
119
+ @abstractmethod
120
+ def metadata(self) -> SearchMetadata:
121
+ """Return metadata describing this search strategy."""
122
+ ...
@@ -0,0 +1,94 @@
1
+ # Copyright 2019-2025 SURF, GÉANT.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
14
+ from sqlalchemy import Select, and_, cast, func, literal, or_, select
15
+ from sqlalchemy.sql.expression import ColumnElement
16
+
17
+ from orchestrator.db.models import AiSearchIndex
18
+ from orchestrator.search.core.types import SearchMetadata
19
+
20
+ from ..pagination import PaginationParams
21
+ from .base import Retriever
22
+
23
+
24
+ class FuzzyRetriever(Retriever):
25
+ """Ranks results based on the max of fuzzy text similarity scores."""
26
+
27
+ def __init__(self, fuzzy_term: str, pagination_params: PaginationParams) -> None:
28
+ self.fuzzy_term = fuzzy_term
29
+ self.page_after_score = pagination_params.page_after_score
30
+ self.page_after_id = pagination_params.page_after_id
31
+
32
+ def apply(self, candidate_query: Select) -> Select:
33
+ cand = candidate_query.subquery()
34
+
35
+ similarity_expr = func.word_similarity(self.fuzzy_term, AiSearchIndex.value)
36
+
37
+ raw_max = func.max(similarity_expr).over(partition_by=AiSearchIndex.entity_id)
38
+ score = cast(
39
+ func.round(cast(raw_max, self.SCORE_NUMERIC_TYPE), self.SCORE_PRECISION), self.SCORE_NUMERIC_TYPE
40
+ ).label(self.SCORE_LABEL)
41
+
42
+ combined_query = (
43
+ select(
44
+ AiSearchIndex.entity_id,
45
+ score,
46
+ func.first_value(AiSearchIndex.value)
47
+ .over(partition_by=AiSearchIndex.entity_id, order_by=[similarity_expr.desc(), AiSearchIndex.path.asc()])
48
+ .label(self.HIGHLIGHT_TEXT_LABEL),
49
+ func.first_value(AiSearchIndex.path)
50
+ .over(partition_by=AiSearchIndex.entity_id, order_by=[similarity_expr.desc(), AiSearchIndex.path.asc()])
51
+ .label(self.HIGHLIGHT_PATH_LABEL),
52
+ )
53
+ .select_from(AiSearchIndex)
54
+ .join(cand, cand.c.entity_id == AiSearchIndex.entity_id)
55
+ .where(
56
+ and_(
57
+ AiSearchIndex.value_type.in_(self.SEARCHABLE_FIELD_TYPES),
58
+ literal(self.fuzzy_term).op("<%")(AiSearchIndex.value),
59
+ )
60
+ )
61
+ .distinct(AiSearchIndex.entity_id)
62
+ )
63
+ final_query = combined_query.subquery("ranked_fuzzy")
64
+
65
+ stmt = select(
66
+ final_query.c.entity_id,
67
+ final_query.c.score,
68
+ final_query.c.highlight_text,
69
+ final_query.c.highlight_path,
70
+ ).select_from(final_query)
71
+
72
+ stmt = self._apply_score_pagination(stmt, final_query.c.score, final_query.c.entity_id)
73
+
74
+ return stmt.order_by(final_query.c.score.desc().nulls_last(), final_query.c.entity_id.asc())
75
+
76
+ @property
77
+ def metadata(self) -> SearchMetadata:
78
+ return SearchMetadata.fuzzy()
79
+
80
+ def _apply_score_pagination(
81
+ self, stmt: Select, score_column: ColumnElement, entity_id_column: ColumnElement
82
+ ) -> Select:
83
+ """Apply standard score + entity_id pagination."""
84
+ if self.page_after_score is not None and self.page_after_id is not None:
85
+ stmt = stmt.where(
86
+ or_(
87
+ score_column < self.page_after_score,
88
+ and_(
89
+ score_column == self.page_after_score,
90
+ entity_id_column > self.page_after_id,
91
+ ),
92
+ )
93
+ )
94
+ return stmt