-
Notifications
You must be signed in to change notification settings - Fork 30
/
map_builder.py
229 lines (193 loc) · 7.56 KB
/
map_builder.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
# coding: utf-8
"""
One-to-One Map Builder and a simple CopyBuilder implementation
"""
import traceback
from abc import ABCMeta, abstractmethod
from datetime import datetime
from math import ceil
from time import time
from typing import Dict, Iterator, List, Optional
from maggma.core import Builder, Store
from maggma.utils import Timeout, grouper
class MapBuilder(Builder, metaclass=ABCMeta):
"""
Apply a unary function to yield a target document for each source document.
Supports incremental building, where a source document gets built only if it
has newer (by last_updated_field) data than the corresponding (by key) target
document.
"""
def __init__(
self,
source: Store,
target: Store,
query: Optional[Dict] = None,
projection: Optional[List] = None,
delete_orphans: bool = False,
timeout: int = 0,
store_process_time: bool = True,
retry_failed: bool = False,
**kwargs,
):
"""
Apply a unary function to each source document.
Args:
source: source store
target: target store
query: optional query to filter source store
projection: list of keys to project from the source for
processing. Limits data transfer to improve efficiency.
delete_orphans: Whether to delete documents on target store
with key values not present in source store. Deletion happens
after all updates, during Builder.finalize.
timeout: maximum running time per item in seconds
store_process_time: If True, add "_process_time" key to
document for profiling purposes
retry_failed: If True, will retry building documents that
previously failed
"""
self.source = source
self.target = target
self.query = query
self.projection = projection
self.delete_orphans = delete_orphans
self.kwargs = kwargs
self.timeout = timeout
self.store_process_time = store_process_time
self.retry_failed = retry_failed
super().__init__(sources=[source], targets=[target], **kwargs)
def ensure_indexes(self):
"""
Ensures indicies on critical fields for MapBuilder
"""
index_checks = [
self.source.ensure_index(self.source.key),
self.source.ensure_index(self.source.last_updated_field),
self.target.ensure_index(self.target.key),
self.target.ensure_index(self.target.last_updated_field),
self.target.ensure_index("state"),
]
if not all(index_checks):
self.logger.warning(
"Missing one or more important indices on stores. "
"Performance for large stores may be severely degraded. "
"Ensure indices on target.key and "
"[(store.last_updated_field, -1), (store.key, 1)] "
"for each of source and target."
)
def prechunk(self, number_splits: int) -> Iterator[Dict]:
"""
Generic prechunk for map builder to perform domain-decompostion
by the key field
"""
self.ensure_indexes()
keys = self.target.newer_in(self.source, criteria=self.query, exhaustive=True)
N = ceil(len(keys) / number_splits)
for split in grouper(keys, N):
yield {"query": {self.source.key: {"$in": list(split)}}}
def get_items(self):
"""
Generic get items for Map Builder designed to perform
incremental building
"""
self.logger.info("Starting {} Builder".format(self.__class__.__name__))
self.ensure_indexes()
keys = self.target.newer_in(self.source, criteria=self.query, exhaustive=True)
if self.retry_failed:
if isinstance(self.query, (dict)):
failed_query = {"$and": [self.query, {"state": "failed"}]}
else:
failed_query = {"state": "failed"}
failed_keys = self.target.distinct(self.target.key, criteria=failed_query)
keys = list(set(keys + failed_keys))
self.logger.info("Processing {} items".format(len(keys)))
if self.projection:
projection = list(
set(self.projection + [self.source.key, self.source.last_updated_field])
)
else:
projection = None
self.total = len(keys)
for chunked_keys in grouper(keys, self.chunk_size):
chunked_keys = list(chunked_keys)
for doc in list(
self.source.query(
criteria={self.source.key: {"$in": chunked_keys}},
properties=projection,
)
):
yield doc
def process_item(self, item: Dict):
"""
Generic process items to process a dictionary using
a map function
"""
self.logger.debug("Processing: {}".format(item[self.source.key]))
time_start = time()
try:
with Timeout(seconds=self.timeout):
processed = dict(self.unary_function(item))
processed.update({"state": "successful"})
for k in [self.source.key, self.source.last_updated_field]:
if k in processed:
del processed[k]
except Exception as e:
self.logger.error(traceback.format_exc())
processed = {"error": str(e), "state": "failed"}
time_end = time()
key, last_updated_field = self.source.key, self.source.last_updated_field
out = {
self.target.key: item[key],
self.target.last_updated_field: self.source._lu_func[0](
item.get(last_updated_field, datetime.utcnow())
),
}
if self.store_process_time:
out["_process_time"] = time_end - time_start
out.update(processed)
return out
def update_targets(self, items: List[Dict]):
"""
Generic update targets for Map Builder
"""
target = self.target
for item in items:
item["_bt"] = datetime.utcnow()
if "_id" in item:
del item["_id"]
if len(items) > 0:
target.update(items)
def finalize(self):
"""
Finalize MapBuilder operations including removing orphaned documents
"""
if self.delete_orphans:
source_keyvals = set(self.source.distinct(self.source.key))
target_keyvals = set(self.target.distinct(self.target.key))
to_delete = list(target_keyvals - source_keyvals)
if len(to_delete):
self.logger.info(
"Finalize: Deleting {} orphans.".format(len(to_delete))
)
self.target.remove_docs({self.target.key: {"$in": to_delete}})
super().finalize()
@abstractmethod
def unary_function(self, item):
"""
ufn: Unary function to process item
You do not need to provide values for
source.key and source.last_updated_field in the output.
Any uncaught exceptions will be caught by
process_item and logged to the "error" field
in the target document.
"""
pass
class CopyBuilder(MapBuilder):
"""Sync a source store with a target store."""
def unary_function(self, item):
"""
Identity function for copy builder map operation
"""
if "_id" in item:
del item["_id"]
return item