| 1 |
from typing import TYPE_CHECKING, Any |
| 2 |
|
| 3 |
from beanie.odm.fields import LinkInfo, LinkTypes |
| 4 |
|
| 5 |
if TYPE_CHECKING: |
| 6 |
from beanie import Document |
| 7 |
|
| 8 |
|
| 9 |
# TODO: check if this is the most efficient way for |
| 10 |
# appending subqueries to the queries var |
| 11 |
|
| 12 |
|
| 13 |
def construct_lookup_queries( |
| 14 |
cls: type["Document"], |
| 15 |
nesting_depth: int | None = None, |
| 16 |
nesting_depths_per_field: dict[str, int] | None = None, |
| 17 |
) -> list[dict[str, Any]]: |
| 18 |
queries: list[dict[str, Any]] = [] |
| 19 |
link_fields = cls.get_link_fields() |
| 20 |
if link_fields is not None: |
| 21 |
for link_info in link_fields.values(): |
| 22 |
final_nesting_depth = ( |
| 23 |
nesting_depths_per_field.get(link_info.field_name, None) |
| 24 |
if nesting_depths_per_field is not None |
| 25 |
else None |
| 26 |
) |
| 27 |
if final_nesting_depth is None: |
| 28 |
final_nesting_depth = nesting_depth |
| 29 |
construct_query( |
| 30 |
link_info=link_info, |
| 31 |
queries=queries, |
| 32 |
database_major_version=cls._database_major_version, |
| 33 |
current_depth=final_nesting_depth, |
| 34 |
) |
| 35 |
return queries |
| 36 |
|
| 37 |
|
| 38 |
def construct_query( |
| 39 |
link_info: LinkInfo, |
| 40 |
queries: list[dict[str, Any]], |
| 41 |
database_major_version: int, |
| 42 |
current_depth: int | None = None, |
| 43 |
): |
| 44 |
if link_info.is_fetchable is False or ( |
| 45 |
current_depth is not None and current_depth <= 0 |
| 46 |
): |
| 47 |
return |
| 48 |
if link_info.link_type in [ |
| 49 |
LinkTypes.DIRECT, |
| 50 |
LinkTypes.OPTIONAL_DIRECT, |
| 51 |
]: |
| 52 |
if database_major_version >= 5 or link_info.nested_links is None: |
| 53 |
lookup_steps = [ |
| 54 |
{ |
| 55 |
"$lookup": { |
| 56 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 57 |
"localField": f"{link_info.lookup_field_name}.$id", |
| 58 |
"foreignField": "_id", |
| 59 |
"as": f"_link_{link_info.field_name}", |
| 60 |
} |
| 61 |
}, |
| 62 |
{ |
| 63 |
"$unwind": { |
| 64 |
"path": f"$_link_{link_info.field_name}", |
| 65 |
"preserveNullAndEmptyArrays": True, |
| 66 |
} |
| 67 |
}, |
| 68 |
{ |
| 69 |
"$addFields": { |
| 70 |
link_info.field_name: { |
| 71 |
"$cond": { |
| 72 |
"if": { |
| 73 |
"$ifNull": [ |
| 74 |
f"$_link_{link_info.field_name}", |
| 75 |
False, |
| 76 |
] |
| 77 |
}, |
| 78 |
"then": f"$_link_{link_info.field_name}", |
| 79 |
"else": f"${link_info.field_name}", |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
}, |
| 84 |
{"$project": {f"_link_{link_info.field_name}": 0}}, |
| 85 |
] # type: ignore |
| 86 |
new_depth = ( |
| 87 |
current_depth - 1 if current_depth is not None else None |
| 88 |
) |
| 89 |
if link_info.nested_links is not None: |
| 90 |
lookup_steps[0]["$lookup"]["pipeline"] = [] # type: ignore |
| 91 |
for nested_link in link_info.nested_links: |
| 92 |
construct_query( |
| 93 |
link_info=link_info.nested_links[nested_link], |
| 94 |
queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore |
| 95 |
database_major_version=database_major_version, |
| 96 |
current_depth=new_depth, |
| 97 |
) |
| 98 |
queries += lookup_steps |
| 99 |
|
| 100 |
else: |
| 101 |
lookup_steps = [ |
| 102 |
{ |
| 103 |
"$lookup": { |
| 104 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 105 |
"let": { |
| 106 |
"link_id": f"${link_info.lookup_field_name}.$id" |
| 107 |
}, |
| 108 |
"as": f"_link_{link_info.field_name}", |
| 109 |
"pipeline": [ |
| 110 |
{ |
| 111 |
"$match": { |
| 112 |
"$expr": {"$eq": ["$_id", "$$link_id"]} |
| 113 |
} |
| 114 |
}, |
| 115 |
], |
| 116 |
} |
| 117 |
}, |
| 118 |
{ |
| 119 |
"$unwind": { |
| 120 |
"path": f"$_link_{link_info.field_name}", |
| 121 |
"preserveNullAndEmptyArrays": True, |
| 122 |
} |
| 123 |
}, |
| 124 |
{ |
| 125 |
"$addFields": { |
| 126 |
link_info.field_name: { |
| 127 |
"$cond": { |
| 128 |
"if": { |
| 129 |
"$ifNull": [ |
| 130 |
f"$_link_{link_info.field_name}", |
| 131 |
False, |
| 132 |
] |
| 133 |
}, |
| 134 |
"then": f"$_link_{link_info.field_name}", |
| 135 |
"else": f"${link_info.field_name}", |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
}, |
| 140 |
{"$project": {f"_link_{link_info.field_name}": 0}}, |
| 141 |
] |
| 142 |
new_depth = ( |
| 143 |
current_depth - 1 if current_depth is not None else None |
| 144 |
) |
| 145 |
for nested_link in link_info.nested_links: |
| 146 |
construct_query( |
| 147 |
link_info=link_info.nested_links[nested_link], |
| 148 |
queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore |
| 149 |
database_major_version=database_major_version, |
| 150 |
current_depth=new_depth, |
| 151 |
) |
| 152 |
queries += lookup_steps |
| 153 |
|
| 154 |
elif link_info.link_type in [ |
| 155 |
LinkTypes.BACK_DIRECT, |
| 156 |
LinkTypes.OPTIONAL_BACK_DIRECT, |
| 157 |
]: |
| 158 |
if database_major_version >= 5 or link_info.nested_links is None: |
| 159 |
lookup_steps = [ |
| 160 |
{ |
| 161 |
"$lookup": { |
| 162 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 163 |
"localField": "_id", |
| 164 |
"foreignField": f"{link_info.lookup_field_name}.$id", |
| 165 |
"as": f"_link_{link_info.field_name}", |
| 166 |
} |
| 167 |
}, |
| 168 |
{ |
| 169 |
"$unwind": { |
| 170 |
"path": f"$_link_{link_info.field_name}", |
| 171 |
"preserveNullAndEmptyArrays": True, |
| 172 |
} |
| 173 |
}, |
| 174 |
{ |
| 175 |
"$addFields": { |
| 176 |
link_info.field_name: { |
| 177 |
"$cond": { |
| 178 |
"if": { |
| 179 |
"$ifNull": [ |
| 180 |
f"$_link_{link_info.field_name}", |
| 181 |
False, |
| 182 |
] |
| 183 |
}, |
| 184 |
"then": f"$_link_{link_info.field_name}", |
| 185 |
"else": f"${link_info.field_name}", |
| 186 |
} |
| 187 |
} |
| 188 |
} |
| 189 |
}, |
| 190 |
{"$project": {f"_link_{link_info.field_name}": 0}}, |
| 191 |
] # type: ignore |
| 192 |
new_depth = ( |
| 193 |
current_depth - 1 if current_depth is not None else None |
| 194 |
) |
| 195 |
if link_info.nested_links is not None: |
| 196 |
lookup_steps[0]["$lookup"]["pipeline"] = [] # type: ignore |
| 197 |
for nested_link in link_info.nested_links: |
| 198 |
construct_query( |
| 199 |
link_info=link_info.nested_links[nested_link], |
| 200 |
queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore |
| 201 |
database_major_version=database_major_version, |
| 202 |
current_depth=new_depth, |
| 203 |
) |
| 204 |
queries += lookup_steps |
| 205 |
|
| 206 |
else: |
| 207 |
lookup_steps = [ |
| 208 |
{ |
| 209 |
"$lookup": { |
| 210 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 211 |
"let": {"link_id": "$_id"}, |
| 212 |
"as": f"_link_{link_info.field_name}", |
| 213 |
"pipeline": [ |
| 214 |
{ |
| 215 |
"$match": { |
| 216 |
"$expr": { |
| 217 |
"$eq": [ |
| 218 |
f"${link_info.lookup_field_name}.$id", |
| 219 |
"$$link_id", |
| 220 |
] |
| 221 |
} |
| 222 |
} |
| 223 |
}, |
| 224 |
], |
| 225 |
} |
| 226 |
}, |
| 227 |
{ |
| 228 |
"$unwind": { |
| 229 |
"path": f"$_link_{link_info.field_name}", |
| 230 |
"preserveNullAndEmptyArrays": True, |
| 231 |
} |
| 232 |
}, |
| 233 |
{ |
| 234 |
"$addFields": { |
| 235 |
link_info.field_name: { |
| 236 |
"$cond": { |
| 237 |
"if": { |
| 238 |
"$ifNull": [ |
| 239 |
f"$_link_{link_info.field_name}", |
| 240 |
False, |
| 241 |
] |
| 242 |
}, |
| 243 |
"then": f"$_link_{link_info.field_name}", |
| 244 |
"else": f"${link_info.field_name}", |
| 245 |
} |
| 246 |
} |
| 247 |
} |
| 248 |
}, |
| 249 |
{"$project": {f"_link_{link_info.field_name}": 0}}, |
| 250 |
] |
| 251 |
new_depth = ( |
| 252 |
current_depth - 1 if current_depth is not None else None |
| 253 |
) |
| 254 |
for nested_link in link_info.nested_links: |
| 255 |
construct_query( |
| 256 |
link_info=link_info.nested_links[nested_link], |
| 257 |
queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore |
| 258 |
database_major_version=database_major_version, |
| 259 |
current_depth=new_depth, |
| 260 |
) |
| 261 |
queries += lookup_steps |
| 262 |
|
| 263 |
elif link_info.link_type in [ |
| 264 |
LinkTypes.LIST, |
| 265 |
LinkTypes.OPTIONAL_LIST, |
| 266 |
]: |
| 267 |
if database_major_version >= 5 or link_info.nested_links is None: |
| 268 |
queries.append( |
| 269 |
{ |
| 270 |
"$lookup": { |
| 271 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 272 |
"localField": f"{link_info.lookup_field_name}.$id", |
| 273 |
"foreignField": "_id", |
| 274 |
"as": link_info.field_name, |
| 275 |
} |
| 276 |
} |
| 277 |
) |
| 278 |
new_depth = ( |
| 279 |
current_depth - 1 if current_depth is not None else None |
| 280 |
) |
| 281 |
if link_info.nested_links is not None: |
| 282 |
queries[-1]["$lookup"]["pipeline"] = [] |
| 283 |
for nested_link in link_info.nested_links: |
| 284 |
construct_query( |
| 285 |
link_info=link_info.nested_links[nested_link], |
| 286 |
queries=queries[-1]["$lookup"]["pipeline"], |
| 287 |
database_major_version=database_major_version, |
| 288 |
current_depth=new_depth, |
| 289 |
) |
| 290 |
else: |
| 291 |
lookup_step = { |
| 292 |
"$lookup": { |
| 293 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 294 |
"let": {"link_id": f"${link_info.lookup_field_name}.$id"}, |
| 295 |
"as": link_info.field_name, |
| 296 |
"pipeline": [ |
| 297 |
{"$match": {"$expr": {"$in": ["$_id", "$$link_id"]}}}, |
| 298 |
], |
| 299 |
} |
| 300 |
} |
| 301 |
new_depth = ( |
| 302 |
current_depth - 1 if current_depth is not None else None |
| 303 |
) |
| 304 |
for nested_link in link_info.nested_links: |
| 305 |
construct_query( |
| 306 |
link_info=link_info.nested_links[nested_link], |
| 307 |
queries=lookup_step["$lookup"]["pipeline"], |
| 308 |
database_major_version=database_major_version, |
| 309 |
current_depth=new_depth, |
| 310 |
) |
| 311 |
queries.append(lookup_step) |
| 312 |
|
| 313 |
elif link_info.link_type in [ |
| 314 |
LinkTypes.BACK_LIST, |
| 315 |
LinkTypes.OPTIONAL_BACK_LIST, |
| 316 |
]: |
| 317 |
if database_major_version >= 5 or link_info.nested_links is None: |
| 318 |
queries.append( |
| 319 |
{ |
| 320 |
"$lookup": { |
| 321 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 322 |
"localField": "_id", |
| 323 |
"foreignField": f"{link_info.lookup_field_name}.$id", |
| 324 |
"as": link_info.field_name, |
| 325 |
} |
| 326 |
} |
| 327 |
) |
| 328 |
new_depth = ( |
| 329 |
current_depth - 1 if current_depth is not None else None |
| 330 |
) |
| 331 |
if link_info.nested_links is not None: |
| 332 |
queries[-1]["$lookup"]["pipeline"] = [] |
| 333 |
for nested_link in link_info.nested_links: |
| 334 |
construct_query( |
| 335 |
link_info=link_info.nested_links[nested_link], |
| 336 |
queries=queries[-1]["$lookup"]["pipeline"], |
| 337 |
database_major_version=database_major_version, |
| 338 |
current_depth=new_depth, |
| 339 |
) |
| 340 |
else: |
| 341 |
lookup_step = { |
| 342 |
"$lookup": { |
| 343 |
"from": link_info.document_class.get_pymongo_collection().name, # type: ignore |
| 344 |
"let": {"link_id": "$_id"}, |
| 345 |
"as": link_info.field_name, |
| 346 |
"pipeline": [ |
| 347 |
{ |
| 348 |
"$match": { |
| 349 |
"$expr": { |
| 350 |
"$in": [ |
| 351 |
"$$link_id", |
| 352 |
f"${link_info.lookup_field_name}.$id", |
| 353 |
] |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
], |
| 358 |
} |
| 359 |
} |
| 360 |
new_depth = ( |
| 361 |
current_depth - 1 if current_depth is not None else None |
| 362 |
) |
| 363 |
for nested_link in link_info.nested_links: |
| 364 |
construct_query( |
| 365 |
link_info=link_info.nested_links[nested_link], |
| 366 |
queries=lookup_step["$lookup"]["pipeline"], |
| 367 |
database_major_version=database_major_version, |
| 368 |
current_depth=new_depth, |
| 369 |
) |
| 370 |
queries.append(lookup_step) |
| 371 |
|
| 372 |
return queries |
| 373 |
|
| 374 |
|
| 375 |
def split_text_query( |
| 376 |
query: dict[str, Any], |
| 377 |
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: |
| 378 |
"""Divide query into text and non-text matches |
| 379 |
|
| 380 |
:param query: Dict[str, Any] - query dict |
| 381 |
:return: Tuple[Dict[str, Any], Dict[str, Any]] - text and non-text queries, |
| 382 |
respectively |
| 383 |
""" |
| 384 |
|
| 385 |
root_text_query_args: dict[str, Any] | None = query.get("$text") |
| 386 |
root_non_text_queries: dict[str, Any] = { |
| 387 |
k: v for k, v in query.items() if k not in {"$text", "$and"} |
| 388 |
} |
| 389 |
|
| 390 |
text_queries: list[dict[str, Any]] = ( |
| 391 |
[{"$text": root_text_query_args}] if root_text_query_args else [] |
| 392 |
) |
| 393 |
non_text_queries: list[dict[str, Any]] = ( |
| 394 |
[root_non_text_queries] if root_non_text_queries else [] |
| 395 |
) |
| 396 |
|
| 397 |
for match_case in query.get("$and", []): |
| 398 |
if "$text" in match_case: |
| 399 |
text_queries.append(match_case) |
| 400 |
else: |
| 401 |
non_text_queries.append(match_case) |
| 402 |
|
| 403 |
return text_queries, non_text_queries |