|
1
|
|
|
from typing import List, Optional |
|
2
|
|
|
|
|
3
|
|
|
from pydantic import BaseModel, Field |
|
4
|
|
|
from pymongo import ASCENDING, DESCENDING, TEXT, IndexModel |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
class Index(BaseModel): |
|
8
|
|
|
name: Optional[str] = Field( |
|
9
|
|
|
default=None, |
|
10
|
|
|
description="Custom name to use for this index - if none is given, a name will be generated.", |
|
11
|
|
|
) |
|
12
|
|
|
|
|
13
|
|
|
fields: List[str] = Field( |
|
14
|
|
|
min_items=1, |
|
15
|
|
|
description=( |
|
16
|
|
|
"Fields to index. Can be prefixed with '+' or '-' to specify index direction as ascending" |
|
17
|
|
|
"or descending. Prefix with '$' to specify text index." |
|
18
|
|
|
), |
|
19
|
|
|
) |
|
20
|
|
|
|
|
21
|
|
|
unique: Optional[bool] = Field(default=False, descrition="If True, creates a uniqueness constraint on the index.") |
|
22
|
|
|
|
|
23
|
|
|
sparse: Optional[bool] = Field( |
|
24
|
|
|
default=False, description="If True, omit from the index any documents that lack the indexed field." |
|
25
|
|
|
) |
|
26
|
|
|
|
|
27
|
|
|
background: Optional[bool] = Field( |
|
28
|
|
|
default=False, description="If True, this index should be created in the background." |
|
29
|
|
|
) |
|
30
|
|
|
|
|
31
|
|
|
# Used to create an expiring (TTL) collection. |
|
32
|
|
|
# MongoDB will automatically delete documents from this collection after <int> seconds. |
|
33
|
|
|
# The indexed field must be a UTC datetime or the data will not expire. |
|
34
|
|
|
expire_after_seconds: Optional[int] = Field( |
|
35
|
|
|
description="Used to create an expiring (TTL) collection. Documents automatically deleted after <int> seconds." |
|
36
|
|
|
) |
|
37
|
|
|
|
|
38
|
|
|
def to_pymongo(self): |
|
39
|
|
|
# Create pymongo index models |
|
40
|
|
|
pymongo_fields = [] |
|
41
|
|
|
for field in self.fields: |
|
42
|
|
|
# Process prefix |
|
43
|
|
|
direction = ASCENDING |
|
44
|
|
|
if field.startswith("-"): |
|
45
|
|
|
direction = DESCENDING |
|
46
|
|
|
field = field[1:] |
|
47
|
|
|
elif field.startswith("+"): |
|
48
|
|
|
field = field[1:] |
|
49
|
|
|
elif field.startswith("$"): |
|
50
|
|
|
direction = TEXT |
|
51
|
|
|
field = field[1:] |
|
52
|
|
|
|
|
53
|
|
|
pymongo_fields.append((field, direction)) |
|
54
|
|
|
|
|
55
|
|
|
return IndexModel( |
|
56
|
|
|
pymongo_fields, |
|
57
|
|
|
unique=self.unique, |
|
58
|
|
|
background=self.background, |
|
59
|
|
|
sparse=self.sparse, |
|
60
|
|
|
expireAfterSeconds=self.expire_after_seconds, |
|
61
|
|
|
) |
|
62
|
|
|
|