/
namespace.py
257 lines (209 loc) · 8.83 KB
/
namespace.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
# Standard Library
import copy
import gzip
import json
from typing import IO
# Third Party Imports
import timy
from arango import ArangoError
from structlog import get_logger
# Local Imports
import bel.db.arangodb as arangodb
import bel.db.elasticsearch as elasticsearch
import bel.utils
from bel.Config import config
# import structlog
# import logging
# log = logging.getLogger(__name__)
log = get_logger()
terms_alias = "terms"
def load_terms(fo: IO, metadata: dict, forceupdate: bool):
"""Load terms into Elasticsearch and ArangoDB
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
fo: file obj - terminology file
metadata: dict containing the metadata for terminology
forceupdate: force full update - e.g. don't leave Elasticsearch indexes
alone if their version ID matches
"""
version = metadata["metadata"]["version"]
# LOAD TERMS INTO Elasticsearch
with timy.Timer("Load Terms") as timer:
es = bel.db.elasticsearch.get_client()
es_version = version.replace("T", "").replace("-", "").replace(":", "")
index_prefix = f"terms_{metadata['metadata']['namespace'].lower()}"
index_name = f"{index_prefix}_{es_version}"
# Create index with mapping
if not elasticsearch.index_exists(es, index_name):
elasticsearch.create_terms_index(es, index_name)
elif forceupdate: # force an update to the index
index_name += "_alt"
elasticsearch.create_terms_index(es, index_name)
else:
return # Skip loading if not forced and not a new namespace
terms_iterator = terms_iterator_for_elasticsearch(fo, index_name)
elasticsearch.bulk_load_docs(es, terms_iterator)
# Remove old namespace index
index_names = elasticsearch.get_all_index_names(es)
for name in index_names:
if name != index_name and index_prefix in name:
elasticsearch.delete_index(es, name)
# Add terms_alias to this index
elasticsearch.add_index_alias(es, index_name, terms_alias)
log.info(
"Load namespace terms",
elapsed=timer.elapsed,
namespace=metadata["metadata"]["namespace"],
)
# LOAD EQUIVALENCES INTO ArangoDB
with timy.Timer("Load Term Equivalences") as timer:
arango_client = arangodb.get_client()
if not arango_client:
print("Cannot load terms without ArangoDB access")
quit()
belns_db = arangodb.get_belns_handle(arango_client)
arangodb.batch_load_docs(
belns_db, terms_iterator_for_arangodb(fo, version), on_duplicate="update"
)
log.info(
"Loaded namespace equivalences",
elapsed=timer.elapsed,
namespace=metadata["metadata"]["namespace"],
)
# Clean up old entries
remove_old_equivalence_edges = f"""
FOR edge in equivalence_edges
FILTER edge.source == "{metadata["metadata"]["namespace"]}"
FILTER edge.version != "{version}"
REMOVE edge IN equivalence_edges
"""
remove_old_equivalence_nodes = f"""
FOR node in equivalence_nodes
FILTER node.source == "{metadata["metadata"]["namespace"]}"
FILTER node.version != "{version}"
REMOVE node IN equivalence_nodes
"""
arangodb.aql_query(belns_db, remove_old_equivalence_edges)
arangodb.aql_query(belns_db, remove_old_equivalence_nodes)
# Add metadata to resource metadata collection
metadata["_key"] = f"Namespace_{metadata['metadata']['namespace']}"
try:
belns_db.collection(arangodb.belns_metadata_name).insert(metadata)
except ArangoError as ae:
belns_db.collection(arangodb.belns_metadata_name).replace(metadata)
def terms_iterator_for_arangodb(fo, version):
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0)
with gzip.open(fo, "rt") as f:
for line in f:
term = json.loads(line)
# skip if not term record (e.g. is a metadata record)
if "term" not in term:
continue
term = term["term"]
species_id = term.get("species_id", None)
# Skip if species not listed in species_list
if species_list and species_id and species_id not in species_list:
continue
source = term["namespace"]
term_id = term["id"]
term_key = arangodb.arango_id_to_key(term_id)
(ns, val) = term_id.split(":", maxsplit=1)
# Add primary ID node
yield (
arangodb.equiv_nodes_name,
{
"_key": term_key,
"name": term_id,
"primary": True,
"namespace": ns,
"source": source,
"version": version,
},
)
# Create Alt ID nodes/equivalences (to support other database equivalences using non-preferred Namespace IDs)
if "alt_ids" in term:
for alt_id in term["alt_ids"]:
# log.info(f'Added {alt_id} equivalence')
alt_id_key = arangodb.arango_id_to_key(alt_id)
yield (
arangodb.equiv_nodes_name,
{
"_key": alt_id_key,
"name": alt_id,
"namespace": ns,
"source": source,
"version": version,
},
)
arango_edge = {
"_from": f"{arangodb.equiv_nodes_name}/{term_key}",
"_to": f"{arangodb.equiv_nodes_name}/{alt_id_key}",
"_key": bel.utils._create_hash(f"{term_id}>>{alt_id}"),
"type": "equivalent_to",
"source": source,
"version": version,
}
yield (arangodb.equiv_edges_name, arango_edge)
# Cross-DB equivalences
if "equivalences" in term:
for eqv in term["equivalences"]:
(ns, val) = eqv.split(":", maxsplit=1)
eqv_key = arangodb.arango_id_to_key(eqv)
yield (
arangodb.equiv_nodes_name,
{
"_key": eqv_key,
"name": eqv,
"namespace": ns,
"source": source,
"version": version,
},
)
arango_edge = {
"_from": f"{arangodb.equiv_nodes_name}/{term_key}",
"_to": f"{arangodb.equiv_nodes_name}/{eqv_key}",
"_key": bel.utils._create_hash(f"{term_id}>>{eqv}"),
"type": "equivalent_to",
"source": source,
"version": version,
}
yield (arangodb.equiv_edges_name, arango_edge)
def terms_iterator_for_elasticsearch(fo: IO, index_name: str):
"""Add index_name to term documents for bulk load"""
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0) # Seek back to beginning of file
with gzip.open(fo, "rt") as f:
for line in f:
term = json.loads(line)
# skip if not term record (e.g. is a metadata record)
if "term" not in term:
continue
term = term["term"]
# Filter species if enabled in config
species_id = term.get("species_id", None)
if species_list and species_id and species_id not in species_list:
continue
all_term_ids = set()
for term_id in [term["id"]] + term.get("alt_ids", []):
all_term_ids.add(term_id)
all_term_ids.add(lowercase_term_id(term_id))
term["alt_ids"] = copy.copy(list(all_term_ids))
yield {
"_op_type": "index",
"_index": index_name,
"_type": "term",
"_id": term["id"],
"_source": copy.deepcopy(term),
}
def lowercase_term_id(term_id: str) -> str:
"""Lowercase the term value (not the namespace prefix)
Args:
term_id (str): term identifier with namespace prefix, e.g. MESH:Atherosclerosis
Returns:
str: lowercased, e.g. MESH:atherosclerosis
"""
(ns, val) = term_id.split(":", maxsplit=1)
term_id = f"{ns}:{val.lower()}"
return term_id