-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathloader.py
executable file
·208 lines (178 loc) · 8.03 KB
/
loader.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
# -*- coding: utf-8 -*-
import csv
import datetime
import json
import os,ssl
import urllib.request
import elasticsearch.helpers
from elasticsearch import Elasticsearch, RequestsHttpConnection, serializer, compat, exceptions, helpers
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context
TYPE = 'record'
# see https://github.com/elastic/elasticsearch-py/issues/374
class JSONSerializerPython2(serializer.JSONSerializer):
"""Override elasticsearch library serializer to ensure it encodes utf characters during json dump.
See original at: https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch/serializer.py#L42
A description of how ensure_ascii encodes unicode characters to ensure they can be sent across the wire
as ascii can be found here: https://docs.python.org/2/library/json.html#basic-usage
"""
def dumps(self, data):
# don't serialize strings
if isinstance(data, compat.string_types):
return data
try:
return json.dumps(data, default=self.default, ensure_ascii=True)
except (ValueError, TypeError) as e:
raise exceptions.SerializationError(data, e)
class ESLoader(object):
def __init__(self, file_location, index_name, drop_existing=False, alias=None, host='localhost:9200'):
"""
:param file_location
:param index_name: the es index to upload to
:param drop_existing:
:param alias: the es alias to associate the index with
"""
self.file_location = file_location
self.index_name = index_name
self.drop_existing = drop_existing
self.alias = alias
self.es = Elasticsearch([host], serializer=JSONSerializerPython2())
def load(self):
if not self.es.indices.exists(self.index_name):
print ('creating index ' + self.index_name)
self.__create_index()
elif self.drop_existing:
print('deleting index ' + self.index_name)
self.es.indices.delete(index=self.index_name)
print ('creating index ' + self.index_name)
self.__create_index()
print('indexing ' + self.file_location)
try:
self.__load_file(self.file_location)
except RuntimeError as e:
print(e)
print("Failed to load file {}".format(file))
print("Indexed " + self.file_location)
def __load_file(self, file):
doc_count = 0
data = []
chunk_size = 100 # Set chunk size to 100 records
with open(file) as f:
print("Starting indexing on " + f.name)
reader = csv.DictReader(f)
for row in reader:
# gracefully handle empty locations
if row['decimalLatitude'] == '' or row['decimalLongitude'] == '':
row['location'] = ''
else:
row['location'] = row['decimalLatitude'] + "," + row['decimalLongitude']
# handle 'unknown' values for yearCollected
if row['yearCollected'].lower() == 'unknown':
row['yearCollected'] = ''
data.append({k: v for k, v in row.items() if v}) # remove empty values
# When chunk_size is reached, send bulk data to Elasticsearch
if len(data) == chunk_size:
helpers.bulk( client=self.es, index=self.index_name, actions=data, raise_on_error=True, request_timeout=60)
doc_count += len(data)
print(f"Indexed {len(data)} documents. Total indexed: {doc_count}")
data = [] # Clear the data list for the next chunk
# Index remaining data if it’s less than chunk_size
if data:
helpers.bulk( client=self.es, index=self.index_name, actions=data, raise_on_error=True, request_timeout=60)
doc_count += len(data)
print(f"Indexed {len(data)} remaining documents. Total indexed: {doc_count}")
print("Finished indexing in", f.name)
return doc_count
def __create_index(self):
request_body = {
"mappings": {
"properties": {
"materialSampleID": {"type": "keyword"},
"principalInvestigator": {"type": "keyword"},
"diseaseTested": {"type": "keyword"},
"diseaseDetected": {"type": "keyword"},
"country": {"type": "keyword"},
"basisOfRecord": {"type": "keyword"},
"order": {"type": "keyword"},
"family": {"type": "keyword"},
"genus": {"type": "keyword"},
"specificEpithet": {"type": "text"},
"scientificName": {"type": "text"},
"verbatimScientificName": {"type": "text"},
"fatal": {"type": "keyword"},
"habitat": {"type": "keyword"},
"sampleType": {"type": "keyword"},
"institutionCode": {"type": "keyword"},
"collectionCode": {"type": "keyword"},
"catalogNumber": {"type": "text"},
"decimalLatitude": { "type": "float" },
"decimalLongitude": { "type": "float" },
"coordinateUncertaintyInMeters": {"type":"text"},
"horizontalDatum": {"type":"text"},
"continentOcean": {"type":"text"},
"stateProvince": {"type":"text"},
"municipality": {"type":"text"},
"county": {"type":"text"},
"locationRemarks": {"type":"text"},
"habitat": {"type":"text"},
"eventRemarks": {"type":"text"},
"georeferenceProtocol": {"type":"text"},
"minimumElevationInMeters": {"type":"text"},
"maximumElevationInMeters": {"type":"text"},
"minimumDepthInMeters": {"type":"text"},
"maximumDepthInMeters": {"type":"text"},
"locationID": {"type":"text"},
"locality": { "type": "keyword" },
"location": { "type": "geo_point" },
"yearCollected": {"type": "integer"},
"monthCollected": {"type": "integer"},
"dayCollected": {"type":"text"},
"verbatimEventDate": {"type":"text"},
"collectorList": {"type": "text"},
"occurrenceID": {"type":"text"},
"otherCatalogNumbers": {"type":"text"},
"fieldNumber": {"type":"text"},
"associatedReferences": {"type":"text"},
"occurrenceRemarks": {"type":"text"},
"infraspecificEpithet": {"type":"text"},
"taxonRemarks": {"type":"text"},
"lifeStage": {"type":"text"},
"establishmentMeans": {"type":"text"},
"sex": {"type":"text"},
"individualCount": {"type":"text"},
"weightUnits": {"type":"text"},
"weight": {"type":"text"},
"lengthUnits": {"type":"text"},
"length": {"type":"text"},
"diseaseLineage": {"type":"text"},
"genotypeMethod": {"type":"text"},
"testMethod": {"type":"text"},
"diseaseTestedPositiveCount": {"type":"text"},
"specimenDisposition": {"type":"text"},
"quantityDetected": {"type":"text"},
"dilutionFactor": {"type":"text"},
"cycleTimeFirstDetection": {"type":"text"},
"zeScore": {"type":"text"},
"diagnosticLab": {"type":"text"},
"projectId": {"type":"text"},
"projectURL": {"type":"text"},
"Sample_bcid": {"type": "text"}
}
}
}
self.es.indices.create(index=self.index_name, body=request_body)
def get_files(dir, ext='csv'):
for root, dirs, files in os.walk(dir):
if len(files) == 0:
print("no files found in {}".format(dir))
for file in files:
if file.endswith(ext):
yield os.path.join(root, file)
index = 'amphibiandisease'
drop_existing = True
alias = 'amphibiandisease'
host = '149.165.170.158:80'
#file_location = 'test.csv'
file_location = 'data/amphibian_disease_data_processed.csv'
loader = ESLoader(file_location, index, drop_existing, alias, host)
loader.load()