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