-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex_utils.py
351 lines (308 loc) · 14.5 KB
/
index_utils.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
#!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = "John Wieczorek"
__contributors__ = "Aaron Steele, John Wieczorek"
__copyright__ = "Copyright 2018 vertnet.org"
__version__ = "index_utils.py 2018-04-07T19:30-3:00"
import json
import logging
import re
import os
from field_utils import index_fields
from datetime import datetime
from google.appengine.api import namespace_manager
from google.appengine.api import search
from mapreduce import operation as op
from mapreduce import context
IS_DEV = 'Development' in os.environ['SERVER_SOFTWARE']
# The expected header of the input stream. This will not be in the stream, but is defined
# here to define the structure of the stream.
HEADER = index_fields()
def build_search_index(readbuffer):
"""
Construct a document from a readbuffer and index it.
"""
# readbuffer should be a tuple from GoogleCloudLineInputReader composed of a
# tuple of the form ((file_name, offset), line)
# Get namespace from mapreduce job and set it.
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
namespace = params['namespace']
index_name = params['index_name']
indexdate = datetime.now().strftime('%Y-%m-%d')
try:
# Get the row out of the input buffer
row=readbuffer[1]
# Create a dictionary from the HEADER and the row
data = get_rec_dict(dict(zip(HEADER, row.split('\t'))))
# s = 'Data from %s' % readbuffer[0][0]
# s += ' offset %s: %s' % (readbuffer[0][0], data)
# logging.warning('%s' % s)
# Create an index document from the row dictionary
doc = index_record(data, indexdate)
# Store the document in the given index
index_doc(doc, index_name, namespace)
except Exception, e:
logging.error('%s\n%s' % (e, readbuffer))
def get_rec_dict(rec):
"""Returns a dictionary of all fields in rec with non-printing characters removed."""
val = {}
for name, value in rec.iteritems():
if value:
# Replace all tabs, vertical tabs, carriage returns, and line feeds
# in field contents with space, then remove leading and trailing spaces.
val[name] = re.sub('[\v\t\r\n]+', ' ', value).strip(' ')
return val
@classmethod
def initalize(cls, resource):
namespace = namespace_manager.get_namespace()
filename = '/gs/vn-indexer/failures-%s-%s.csv' % (namespace, resource)
log = cls.get_or_insert(key_name=filename, namespace=namespace)
return log
def index_record(data, indexdate, issue=None):
"""
Creates a document ready to index from the given input data. This is where the work
is done to construct the document.
"""
keyname, iptrecordid, icode, collectioncode, catalognumber, \
gbifdatasetid, gbifpublisherid, networks, \
license, migrator, vntype, orgcountry, orgstateprovince, \
dctype, basisofrecord, \
continent, country, stateprov, county, municipality, \
islandgroup, island, waterbody, locality, \
decimallatitude, decimallongitude, coordinateuncertaintyinmeters, \
geodeticdatum, georeferencedby, georeferenceverificationstatus, \
kingdom, phylum, classs, order, family, \
genus, specificepithet, infraspecificepithet, \
scientificname, vernacularname, typestatus, \
recordedby, recordnumber, fieldnumber, establishmentmeans, \
bed, formation, group, member, \
sex, lifestage, preparations, reproductivecondition, \
year, month, day, startdayofyear, enddayofyear, eventdate, \
haslicense, hasmedia, hastissue, hastypestatus, \
isfossil, isarch, mappable, wascaptive, wasinvasive, \
haslength, haslifestage, hasmass, hassex, \
lengthinmm, lengthtype, massing, rank, hashid = map(data.get,
['keyname', 'iptrecordid', 'icode', 'collectioncode', 'catalognumber',
'gbifdatasetid', 'gbifpublisherid', 'networks',
'license', 'migrator', 'vntype', 'orgcountry', 'orgstateprovince',
'dctype', 'basisofrecord',
'continent', 'country', 'stateprovince', 'county', 'municipality',
'islandgroup', 'island', 'waterbody', 'locality',
'decimallatitude', 'decimallongitude', 'coordinateuncertaintyinmeters',
'geodeticdatum', 'georeferencedby', 'georeferenceverificationstatus',
'kingdom', 'phylum', 'class', 'order', 'family',
'genus', 'specificepithet', 'infraspecificepithet',
'scientificname', 'vernacularname', 'typestatus',
'recordedby', 'recordnumber', 'fieldnumber', 'establishmentmeans',
'bed', 'formation', 'group', 'member',
'sex', 'lifestage', 'preparations', 'reproductivecondition',
'year', 'month', 'day', 'startdayofyear', 'enddayofyear', 'eventdate',
'haslicense', 'hasmedia', 'hastissue', 'hastypestatus',
'isfossil', 'isarch', 'mappable', 'wascaptive', 'wasinvasive',
'haslength', 'haslifestage', 'hasmass', 'hassex',
'lengthinmm', 'lengthtype', 'massing', 'rank', 'hashid'])
# # The data type on eventdate is date, so turn the input string into a date.
# eventdate = _w3c_eventdate(data)
# The data type for location is a GeoPoint. Create one from lat and lng ignoring
# datum. To do this correctly, the lat and lng should be transformed to WGS84 before
# this.
location = _location(decimallatitude, decimallongitude)
# Do full text indexing on all the verbatim fields of the record.
# Index specific key fields for explicit searches on their content.
doc = search.Document(
doc_id=keyname,
rank=as_int(rank),
fields=[
### RECORD-LEVEL ###
search.TextField(name='institutioncode', value=icode),
search.TextField(name='collectioncode', value=collectioncode),
search.TextField(name='catalognumber', value=catalognumber),
search.AtomField(name='dctype', value=dctype),
search.TextField(name='license', value=license),
search.AtomField(name='basisofrecord', value=basisofrecord),
### OCCURRENCE ###
search.AtomField(name='iptrecordid', value=iptrecordid),
search.TextField(name='recordedby', value=recordedby),
search.TextField(name='recordnumber', value=recordnumber),
search.TextField(name='fieldnumber', value=fieldnumber),
search.TextField(name='establishmentmeans', value=establishmentmeans),
search.TextField(name='sex', value=sex),
search.TextField(name='lifestage', value=lifestage),
search.TextField(name='preparations', value=preparations),
search.TextField( \
name='reproductivecondition', value=reproductivecondition),
### EVENT (for year, month, day, see below) ###
search.TextField(name='eventdate', value=eventdate),
### LOCATION (for coordinateuncertaintyinmeters, see below) ###
search.TextField(name='continent', value=continent),
search.TextField(name='country', value=country),
search.TextField(name='stateprovince', value=stateprov),
search.TextField(name='county', value=county),
search.TextField(name='municipality', value=municipality),
search.TextField(name='island', value=island),
search.TextField(name='islandgroup', value=islandgroup),
search.TextField(name='waterbody', value=waterbody),
search.TextField(name='locality', value=locality),
search.TextField(name='geodeticdatum', value=geodeticdatum),
search.TextField(name='georeferencedby', value=georeferencedby),
search.TextField( \
name='georeferenceverificationstatus', \
value=georeferenceverificationstatus),
### GEOLOGICAL CONTEXT ###
search.TextField(name='bed', value=bed),
search.TextField(name='formation', value=formation),
search.TextField(name='group', value=group),
search.TextField(name='member', value=member),
### IDENTIFICATION ###
search.TextField(name='typestatus', value=typestatus),
### TAXON ###
search.AtomField(name='kingdom', value=kingdom),
search.AtomField(name='phylum', value=phylum),
search.AtomField(name='class', value=classs),
search.AtomField(name='order', value=order),
search.AtomField(name='family', value=family),
search.AtomField(name='genus', value=genus),
search.TextField(name='specificepithet', value=specificepithet),
search.TextField(name='infraspecificepithet', value=infraspecificepithet),
search.TextField(name='scientificname', value=scientificname),
search.TextField(name='vernacularname', value=vernacularname),
### TRAIT (for lengthinmm, massing, see below) ###
search.TextField(name='lengthtype', value=lengthtype),
### DATA SET ###
search.AtomField(name='gbifdatasetid', value=gbifdatasetid),
search.AtomField(name='gbifpublisherid', value=gbifpublisherid),
search.TextField(name='lastindexed', value=indexdate),
search.TextField(name='networks', value=networks),
search.TextField(name='migrator', value=migrator),
search.TextField(name='orgcountry', value=orgcountry),
search.TextField(name='orgstateprovince', value=orgstateprovince),
### BOOLEANS ###
search.AtomField(name='haslicense', value=haslicense),
search.AtomField(name='hasmedia', value=hasmedia),
search.AtomField(name='hastissue', value=hastissue),
search.AtomField(name='hastypestatus', value=hastypestatus),
search.AtomField(name='isfossil', value=isfossil),
search.AtomField(name='isarch', value=isarch),
search.AtomField(name='mappable', value=mappable),
search.AtomField(name='wascaptive', value=wascaptive),
search.AtomField(name='wasinvasive', value=wasinvasive),
search.AtomField(name='haslength', value=haslength),
search.AtomField(name='haslifestage', value=haslifestage),
search.AtomField(name='hasmass', value=hasmass),
search.AtomField(name='hassex', value=hassex),
### INDEX ###
search.NumberField(name='rank', value=as_int(rank)),
search.AtomField(name='vntype', value=vntype),
search.NumberField(name='hashid', value=as_int(hashid)),
search.TextField(name='verbatim_record', value=json.dumps(data))])
v = as_int(year)
if v is not None:
doc.fields.append(search.NumberField( \
name='year', value=v))
v = as_int(month)
if v is not None:
doc.fields.append(search.NumberField( \
name='month', value=v))
v = as_int(day)
if v is not None:
doc.fields.append(search.NumberField( \
name='day', value=v))
v = as_int(startdayofyear)
if v is not None:
doc.fields.append(search.NumberField( \
name='startdayofyear', value=v))
v = as_int(enddayofyear)
if v is not None:
doc.fields.append(search.NumberField( \
name='enddayofyear', value=v))
v = as_float(lengthinmm)
if v is not None:
doc.fields.append(search.NumberField( \
name='lengthinmm', value=v))
v = as_float(massing)
if v is not None:
doc.fields.append(search.NumberField( \
name='massing', value=v))
if location is not None:
doc.fields.append(search.GeoField(name='location', value=location))
v = as_int(coordinateuncertaintyinmeters)
if v is not None:
doc.fields.append(search.NumberField( \
name='coordinateuncertaintyinmeters', value=v))
return doc
def index_doc(doc, index_name, namespace, issue=None):
"""
Index a document in the given index and namespace.
"""
max_retries = 2
retry_count = 0
while retry_count < max_retries:
try:
search.Index(index_name, namespace=namespace).put(doc)
# logging.warning('Indexed doc:\n%s' % doc )
return # Successfully indexed document.
except Exception, e:
logging.error('Put #%s failed for doc %s (%s)' % (retry_count, doc.doc_id, e))
retry_count += 1
logging.error('Failed to index: %s' % doc.doc_id)
def as_float(str):
""" Convert a string into a float, if possible.
parameters:
str - string (required)
returns:
a float equivalent of the string, or None
"""
try:
return float(str)
except:
return None
def as_int(str):
""" Convert a string into an int, if possible.
parameters:
str - string (required)
returns:
an int equivalent of the string, or None
"""
try:
return int(str)
except:
return None
def _location(lat, lon):
"""Return a GeoPoint representation of lat and long, if possible,
otherwise return None.
"""
try:
return apply(search.GeoPoint, map(float, [lat, lon]))
except:
return None
# def _w3c_eventdate(rec):
# """Construct a W3C datetime from year, month, and day, if possible."""
# if rec.has_key('day') is False:
# return None
# if len(rec['day']) == 0:
# return None
# if rec.has_key('month') is False:
# return None
# if len(rec['month']) == 0:
# return None
# if rec.has_key('year') is False:
# return None
# if len(rec['year']) == 0:
# return None
# isodate = '%s-%s-%s' % (rec['year'], rec['month'], rec['day'])
#
# try:
# return datetime.strptime(isodate, '%Y-%m-%d').date()
# except:
# return None