This repository has been archived by the owner on Jan 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prep_test_data.py
executable file
·506 lines (434 loc) · 17.1 KB
/
prep_test_data.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#!/usr/bin/env python3
"""
Test Data Prep Tool
This tool will fetch data to use in BioThings App Test test cases, given
specification, of such data.
The configuration file uses TOML. Documented below. If a value is populated,
then that will be the default value.
[elasticsearch]
# host name or IP address of Elasticsearch instance
host = 127.0.0.1
# port number of elastic search
port = 9200
# name of the index to pull data from, required
index =
[global]
# list of _id that will be ignored from the query process. This does not
# affect the dump process
ignore_doc_id = []
# list of _id that will be removed from doc_id in each query.
# typically only required when the origin data changes and such document
# is no longer found.
# CAUTION: if you remove an _id, it will not be dumped. If this is used
# in any of the tests, you will need to update the test accordingly
remove_doc_id = []
[queries]
# this section is for individual queries. they are all in their
# separate tables
[queries.example_query_name]
# indicates whether this query is automatically generated
auto_gen = false
# body of the query sent to the ES search endpoint, JSON in string
query = '''
{
"query": {
"exists": {
"field": "name.of.field"
}
}
}
'''
# of course you can do it in one line, or use more complex queries and
# also filters, anything that you can send to that endpoint that yields
# the typical response
# list of query results, if this is empty, there should be a comment
# explaining that no matches was found at the time of query
doc_id =
# indication that no result was found
no_match = false
# force this query to be run again even if results are present
force_requery = false
Not all features have been implemented yet.
"""
import argparse
import hashlib
import json
import logging
import os
import pickle
import sys
from datetime import datetime
from typing import Any, Dict, List, Optional, Set, FrozenSet
from functools import reduce
import requests
from urllib.parse import urljoin
import tomlkit
from pprint import pprint
class MiniClient:
"""
Miniature ES client
Due to handling and testing multiple versions of ES Python client and
ES server combination is harder, and only a small subset of things are used
in this script, hence this client
"""
def __init__(self, host: str, port: int, timeout: float = 30.0):
self._logger = logging.getLogger('mini_client')
self._host = f'http://{host}:{port}'
self._session = requests.Session() # so the conn. gets reused
self._timeout = timeout
ver_nums = self.api_req('get', '')['version']['number'].split('.')
self.major_version = int(ver_nums[0])
self.minor_version = int(ver_nums[1])
if self.major_version < 6 or \
self.major_version == 6 and self.minor_version < 8:
raise RuntimeError("Requires ES6.8+")
elif self.major_version > 7:
self._logger.warning("Only tested with ES6.8-ES7, running: %s",
ver_nums.join('.'))
# inlined version fn, only used once
def api_req(self, method: str, endpoint: str = '', data=None, params=None):
url = urljoin(self._host, endpoint)
r = self._session.request(method=method, url=url,
json=data, params=params,
timeout=self._timeout)
if not 200 <= r.status_code < 300:
if r.status_code == 400:
pprint(r.json())
raise RuntimeError
return r.json()
def search(self, body, index: str, scroll: Optional[str] = None,
size: int = 1000):
params = {"size": size}
if scroll:
params.update(scroll=scroll)
ret = self.api_req('get', f'/{index}/_search',
data=body, params=params)
return ret
def scroll(self, scroll_id: str, scroll: str):
# ES requires the scroll parameter every time or weird things happen
return self.api_req('get', '/_search/scroll',
data={'scroll_id': scroll_id,
'scroll': scroll}
)
def get_mapping(self, index: str):
if self.major_version == 6:
resp = self.api_req('get', f'/{index}',
params={'include_type_name': 'false'})
else:
resp = self.api_req('get', f'/{index}')
if len(resp) != 1:
logging.warning("%s is alias with more than one index?", index)
resp = next(iter(resp.values())) # pull the value
static_settings = (
'number_of_shards',
'number_of_routing_shards',
'shard',
'codec',
'routing_partition_size',
'soft_deletes',
'load_fixed_bitset_filters_eagerly',
'hidden',
)
delete_settings = (
'provided_name',
'creation_date',
'uuid',
'version',
'number_of_replicas',
)
for k in static_settings + delete_settings:
r = resp['settings']['index'].pop(
k, None
)
if r:
logging.info("key settings.index.%s deleted", k)
return resp
def clear_scroll(self, scroll_id: str) -> None:
self.api_req('delete', '/_search/scroll',
data={'scroll_id': scroll_id})
def get_doc_type(self, index: str) -> str:
if self.major_version >= 7:
raise RuntimeError("Document type removed in ES7+")
mapping = self.api_req('get', f'/{index}')
mapping = next(iter(mapping.values()))['mappings']
return next(iter(mapping.keys()))
def get_source(self, index: str, doc_id):
if self.major_version > 6:
src = self.api_req('get', f'/{index}/_source/{doc_id}')
else:
doc_type = self.get_doc_type(index)
src = self.api_req('get', f'/{index}/{doc_type}/{doc_id}/_source')
return src
def write_ckpt(o, path: str):
with open(path, 'wb') as f:
pickle.dump(o, f)
def load_ckpt(path: str):
with open(path, 'rb') as f:
return pickle.load(f)
def dict_hash(d: dict) -> bytes:
js = json.dumps(d, sort_keys=True)
return hashlib.sha256(js.encode('ascii')).digest()
def get_fields(d: Dict[str, Any], parents: Optional[list] = None):
if not parents:
parents = []
for k, v in d.items():
field_name = '.'.join(parents + [k])
if k.startswith('_') or k in ['all']:
continue
if isinstance(v, dict):
if 'properties' in v:
yield from get_fields(v['properties'], parents + [k])
elif 'type' in v: # okay when the field name is 'type'
yield field_name
else:
logging.warning("unable to handle %s: %s", field_name, v)
def generate_query_all_fields(fields: List[str], page_size: int) -> List[dict]:
queries = []
for field_name in fields:
queries.append({
'query': {'exists': {'field': field_name}},
'size': page_size,
'_source': False
})
return queries
def dump_ids_from_queries(client: MiniClient,
index: str, queries: List[dict], target_size: int,
checkpoint_path: Optional[str] = None,
size: Optional[int] = 1000) \
-> Dict[str, Set[int]]:
id_to_query = {}
done = set()
if checkpoint_path:
try:
id_to_query, done = load_ckpt(checkpoint_path)
except FileNotFoundError:
pass
num_total = len(queries)
try:
for query_idx, query in enumerate(queries):
query_hash = dict_hash(query)
if query_hash in done:
logging.info("Skipping query %d because it was done", query_idx)
continue
query.update(_source=False)
logging.info("Processing query %d of %d", query_idx, num_total)
query_hit_running_total = 0
resp = client.search(query, index=index, scroll='5m', size=size)
sc_id = resp['_scroll_id']
while len(resp['hits']['hits']) > 0:
for hit in resp['hits']['hits']:
id_to_query.setdefault(hit['_id'], set()).add(query_idx)
query_hit_running_total += 1
logging.info("Obtained %d queries", query_hit_running_total)
if query_hit_running_total >= target_size:
# stop early if we have enough, or scroll through
logging.info(
"Stop scrolling early because got %d results for query %d",
query_hit_running_total, query_idx
)
break
resp = client.scroll(scroll_id=sc_id, scroll='1m')
sc_id = resp['_scroll_id']
else:
logging.info("End of results, got %d", query_hit_running_total)
client.clear_scroll(scroll_id=sc_id)
done.add(query_hash)
except KeyboardInterrupt:
logging.warning("Got KeyboardInterrupt")
if checkpoint_path:
write_ckpt((id_to_query, done), checkpoint_path)
sys.exit(0)
logging.info("done with all queries")
if checkpoint_path:
write_ckpt((id_to_query, done), checkpoint_path)
return id_to_query
def minimal_cover_set(subsets: Dict[FrozenSet[int], str])\
-> Dict[str, FrozenSet[int]]:
universe: FrozenSet[int] = reduce(lambda a, b: a | b, subsets.keys())
covered = set()
picked = {}
while covered != universe:
uncovered = universe - covered
remove_list = []
coverage = {}
for subset, doc_id in subsets.items():
can_cover = len(uncovered & subset)
if can_cover == 0:
remove_list.append(subset)
continue
coverage[subset] = can_cover
pick = sorted(coverage, key=lambda k: coverage[k])[-1]
covered |= pick
picked[subsets[pick]] = pick
for rm_subset in remove_list:
subsets.pop(rm_subset)
return picked
def dump_mapping_and_docs(client: MiniClient, index: str, ids: List[str],
output_dir: str) -> None:
os.makedirs(output_dir, exist_ok=True)
setting = client.get_mapping(index)
with open(os.path.join(output_dir, 'data.json'), 'w') as file:
json.dump(setting, file, indent=2)
with open(os.path.join(output_dir, 'data.ndjson'), 'w') as file:
for doc_id in ids:
doc_src = client.get_source(index=index, doc_id=doc_id)
json.dump({"index": {"_id": doc_id}}, file)
file.write('\n')
json.dump(doc_src, file)
file.write('\n')
def dump_documents(args: argparse.Namespace):
fn_mapping = f'{args.output_prefix}.json'
fn_docs = f'{args.output_prefix}.ndjson'
if os.path.exists(fn_mapping) or os.path.exists(fn_docs):
# obviously we can overwrite the files that pops into existence
# after the check, but we don't care
logging.error("File already exists!")
sys.exit(-1)
with open(args.input) as f:
t_doc = tomlkit.loads(f.read())
doc_ids = set()
for q_body in t_doc['queries'].values():
ids = q_body.get('doc_id', [])
doc_ids |= set(ids)
client = MiniClient(args.host, args.port)
mapping = client.get_mapping(args.index)
with open(fn_mapping, 'x') as f:
json.dump(mapping, f)
with open(fn_docs, 'x') as f:
for doc_id in doc_ids:
src = client.get_source(args.index, doc_id)
json.dump({"index": {"_id": doc_id}}, f)
f.write('\n')
json.dump(src, f)
f.write('\n')
def perform_query(args: argparse.Namespace):
client = MiniClient(args.host, args.port)
dt_str = get_iso8601_dt_str()
# dump mapping
with open(args.queries) as f:
doc = tomlkit.loads(f.read())
all_queries = []
query_names = []
# TODO: pre-populate with existing results -- if something we have
# already satisfies the new queries, use that instead
for query_name, q_body in doc['queries'].items():
if 'doc_id' in q_body and not q_body.get('re-query', False):
continue
all_queries.append(json.loads(q_body['query']))
query_names.append(query_name)
# FIXME: checkpoint file name
id_to_query = dump_ids_from_queries(client, args.index,
all_queries, args.num,
checkpoint_path='ckpt.pkl',
size=args.size)
# do a deduplication before we do the set cover problem
# better (?) if we consider superset/subset before doing the
# minimal set cover
subsets = {}
universe = set()
for doc_id, subset in id_to_query.items():
universe |= subset
subsets[frozenset(subset)] = doc_id
missing = set(range(len(all_queries))) - universe
missing_cmt = tomlkit.comment(f"No match was found on {dt_str}")
for missing_id in missing:
query_name = query_names[missing_id]
doc['queries'][query_name].add('doc_id', [])
doc['queries'][query_name].add(missing_cmt)
picked_ids = minimal_cover_set(subsets)
found_cmt = tomlkit.comment(f"Updated on {dt_str}")
for doc_id, subsets in picked_ids.items():
for query_idx in subsets:
query_name = query_names[query_idx]
q_body = doc['queries'][query_name]
docs = q_body.get('doc_id', [])
docs.append(doc_id)
found_cmt = tomlkit.comment(f"{doc_id} added on {dt_str}")
# if 'doc_id' in q_body:
# q_body.remove('doc_id') # here is the thing, pop is broken
q_body['doc_id'] = docs
q_body.add(found_cmt)
# FIXME: can't precisely control the presentation,
# tomlkit is really lacking in terms of documentation
# but on the other hand it is kind of insane to use it this way
with open(args.queries, 'w') as f:
f.write(tomlkit.dumps(doc))
def generate_queries(args: argparse.Namespace):
client = MiniClient(args.host, args.port)
# dump mapping
mappings = client.get_mapping(index=args.index)['mappings']
all_fields = list(get_fields(mappings['properties']))
doc = tomlkit.document()
dt_str = get_iso8601_dt_str()
comment = tomlkit.comment(f"Automatically generated on {dt_str}")
# build all queries
queries = tomlkit.table()
for field_name in all_fields:
t = tomlkit.table()
t.add(comment)
replace_name = field_name.replace('.', '_')
query_name = f'field_{replace_name}_exists'
query = json.dumps({
'query': {'exists': {'field': field_name}}
})
t.add('query', query)
t.add('auto_gen', True)
queries.add(query_name, t)
doc["queries"] = queries
with open(args.output, 'w') as f:
f.write(tomlkit.dumps(doc))
def get_iso8601_dt_str():
return datetime.now().replace(microsecond=0).astimezone().isoformat()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--host', '-s', metavar='ES_HOST', type=str, default='127.0.0.1',
help="Elasticsearch host to pull data from"
)
parser.add_argument(
'--port', '-p', metavar='ES_PORT', type=int, default=9200,
)
parser.add_argument(
'--index', '-i', metavar='INDEX', type=str, required=True
)
parser.add_argument('--verbose', '-v', action='count', default=0)
subparsers = parser.add_subparsers(dest="cmd")
generate_parser = subparsers.add_parser('generate')
generate_parser.add_argument(
'--output', '-o', metavar='OUTPUT', type=str, required=True
)
query_parser = subparsers.add_parser('query')
query_parser.add_argument(
'--queries', '-q', metavar='Q'
)
query_parser.add_argument(
'--num', '-n', metavar='N', type=int, default=10000,
help="target number of _id to obtain, may get more or less than N"
)
query_parser.add_argument(
'--size', '-s', metavar='SIZE', type=int, default=1000,
help="number of results from ES per request"
)
query_parser.add_argument(
'--checkpoint', '-c', metavar='CHECKPOINT_FILE', type=str,
required=False
)
dump_parser = subparsers.add_parser('dump')
dump_parser.add_argument(
'--input', '-i', metavar='INPUT', type=str, required=True,
)
dump_parser.add_argument(
'--output-prefix', '-o', metavar='OUTPUT_PREFIX', type=str,
required=True,
)
args = parser.parse_args()
if args.verbose == 1:
logging.getLogger().setLevel(logging.INFO)
elif args.verbose >= 2:
logging.getLogger().setLevel(logging.DEBUG)
cmd_map = {
'generate': generate_queries,
'query': perform_query,
'dump': dump_documents
}
cmd_map[args.cmd](args)