Project

General

Profile

1
from json import JSONEncoder
2

    
3
import sys
4

    
5
import re
6
from elasticsearch import Elasticsearch
7
from elasticsearch_dsl import *
8

    
9
import os
10
from os import path
11

    
12
pid_resolver = {
13
    "pdb": "http://www.rcsb.org/pdb/explore/explore.do?structureId=%s",
14
    "ncbi-n": "http://www.ncbi.nlm.nih.gov/gquery/?term=%s",
15
    "pmid": "http://www.ncbi.nlm.nih.gov/pubmed/%s",
16
    "pmcid": "http://www.ncbi.nlm.nih.gov/pmc/articles/%s",
17
    "pubmedid": "http://www.ncbi.nlm.nih.gov/pubmed/%s",
18
    "doi": "http://dx.doi.org/%s",
19
    "genbank": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
20
    "nuccore": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
21
    "swiss-prot": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
22
    "arrayexpress": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
23
    "biomodels": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
24
    "bmrb": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
25
    "ena": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
26
    "geo": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
27
    "ensembl": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
28
    "mgi": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
29
    "bind": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
30
    "pride": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
31
    "ddbj": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
32
    "bioproject": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
33
    "embl": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
34
    "sra": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
35
}
36

    
37

    
38
def resolveIdentifier(pid, pid_type):
39

    
40

    
41
    if pid_type != None:
42
        regex = r"\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\'<>])\S)+)\b"
43
        if re.match(regex,pid):
44
            print "It should be doi"
45
            pid_type='doi'
46

    
47

    
48

    
49
        if pid_type.lower() in pid_resolver:
50
            return pid_resolver[pid_type.lower()] % pid
51
        else:
52
            if pid_type.lower() == 'openaire':
53
                return "https://www.openaire.eu/search/publication?articleId=%s" % pid.replace('oai:dnet:', '')
54
            else:
55
                return "http://identifiers.org/%s:%s" % (pid_type, pid)
56
    return ""
57

    
58

    
59
def get_property():
60
    f = open(path.join(os.path.dirname(os.path.realpath(__file__)), '../../api.properties'))
61
    p = {}
62
    for line in f:
63
        data = line.strip().split("=")
64
        p[data[0].strip()] = data[1].strip()
65
    return p
66

    
67

    
68
def create_typology_filter(value):
69
    return Q('match', typology=value)
70

    
71

    
72
def create_pid_type_filter(value):
73
    args = {'localIdentifier.type': value}
74
    return Q('nested', path='localIdentifier', query=Q('bool', must=[Q('match', **args)]))
75

    
76

    
77
def create_pid_query(value):
78
    args = {'localIdentifier.id': value}
79
    return Q('nested', path='localIdentifier', query=Q('bool', must=[Q('match', **args)]))
80

    
81

    
82
def create_publisher_filter(value):
83
    return Q('match', publisher=value)
84

    
85

    
86
def create_datasource_filter(value):
87
    args = {'datasources.datasourceName': value}
88
    return Q('nested', path='datasources', query=Q('bool', must=[Q('match', **args)]))
89

    
90

    
91
class DLIESResponseEncoder(JSONEncoder):
92
    def default(self, o):
93
        return o.__dict__
94

    
95

    
96
class DLIESResponse(object):
97
    def __init__(self, facet=None, total=0, hits=[]):
98
        if facet is None:
99
            facet = dict(pid=[], typology=[], datasource=[])
100
        self.facet = facet
101
        self.total = total
102
        self.hits = hits
103

    
104

    
105
class DLIESConnector(object):
106
    def __init__(self):
107
        props = get_property()
108
        self.index_host = [x.strip() for x in props['es_index'].split(',')]
109
        self.client = Elasticsearch(hosts=self.index_host)
110
        self.index_name = props['api.index']
111

    
112
    def query_by_id(self, id):
113
        s = Search(using=self.client, index=self.index_name).doc_type('object')
114
        s = s.query(create_pid_query(id))
115
        s.aggs.bucket('typologies', 'terms', field='typology')
116
        s.aggs.bucket('all_datasources', 'nested', path='datasources').bucket('all_names', 'terms',
117
                                                                              field='datasources.datasourceName')
118
        s.aggs.bucket('all_publisher', 'terms', field='publisher')
119
        s.aggs.bucket('all_pids', 'nested', path='localIdentifier').bucket('all_types', 'terms',
120
                                                                           field='localIdentifier.type')
121
        response = s.execute()
122

    
123
        hits = []
124

    
125
        for index_result in response.hits:
126
            input_source = index_result.__dict__['_d_']
127
            fixed_titles = []
128

    
129
            for ids in input_source.get('localIdentifier', []):
130
                ds = resolveIdentifier(ids['id'], ids['type'])
131
                ids['url'] = ds
132
            for t in input_source.get('title', []):
133
                if len(t) > 0 and t[0] == '"' and t[-1] == '"':
134
                    fixed_titles.append(t[1:-1])
135
                else:
136
                    fixed_titles.append(t)
137
            input_source['title'] = fixed_titles
138
            hits.append(input_source)
139

    
140
        pid_types = []
141
        for tag in response.aggs.all_pids.all_types.buckets:
142
            pid_types.append(dict(key=tag.key, count=tag.doc_count))
143

    
144
        datasources = []
145
        for tag in response.aggs.all_datasources.all_names.buckets:
146
            datasources.append(dict(key=tag.key, count=tag.doc_count))
147

    
148
        typologies = []
149
        for tag in response.aggs.typologies.buckets:
150
            typologies.append(dict(key=tag.key, count=tag.doc_count))
151

    
152
        publishers = []
153
        for tag in response.aggs.all_publisher.buckets:
154
            if len(tag.key) > 0:
155
                publishers.append(dict(key=tag.key, count=tag.doc_count))
156

    
157
        return DLIESResponse(total=response.hits.total,
158
                             facet=dict(pid=pid_types, typology=typologies, datasource=datasources,
159
                                        publishers=publishers), hits=hits)
160

    
161
    def simple_query(self, textual_query, start=None, end=None, user_filter=None):
162
        s = Search(using=self.client, index=self.index_name).doc_type('object')
163
        q = Q('match', _all=textual_query)
164
        s.aggs.bucket('typologies', 'terms', field='typology')
165
        s.aggs.bucket('all_datasources', 'nested', path='datasources').bucket('all_names', 'terms',
166
                                                                              field='datasources.datasourceName')
167
        s.aggs.bucket('all_publisher', 'terms', field='publisher')
168

    
169
        filter_queries = []
170
        if user_filter is not None and len(user_filter) > 0:
171
            for f in user_filter.split('__'):
172
                filter_key = f.split('_')[0]
173
                filter_value = f.split('_')[1]
174
                if filter_key == 'typology':
175
                    filter_queries.append(create_typology_filter(filter_value))
176
                elif filter_key == 'datasource':
177
                    filter_queries.append(create_datasource_filter(filter_value))
178
                elif filter_key == 'pidtype':
179
                    filter_queries.append(create_pid_type_filter(filter_value))
180
                elif filter_key == 'publisher':
181
                    filter_queries.append(create_publisher_filter(filter_value))
182

    
183
        if len(filter_queries) > 0:
184
            s = s.query(q).filter(Q('bool', must=filter_queries))
185
        else:
186
            s = s.query(q)
187

    
188
        s.aggs.bucket('all_pids', 'nested', path='localIdentifier').bucket('all_types', 'terms',
189
                                                                           field='localIdentifier.type')
190

    
191
        if start is not None:
192
            if end is None:
193
                end = start + 10
194
            s = s[start:end]
195
        response = s.execute()
196

    
197
        hits = []
198

    
199
        for index_result in response.hits:
200
            input_source = index_result.__dict__['_d_']
201
            fixed_titles = []
202

    
203
            for ids in input_source.get('localIdentifier', []):
204
                ds = resolveIdentifier(ids['id'], ids['type'])
205
                ids['url'] = ds
206
            for t in input_source.get('title', []):
207
                if len(t) > 0 and t[0] == '"' and t[-1] == '"':
208
                    fixed_titles.append(t[1:-1])
209
                else:
210
                    fixed_titles.append(t)
211
            input_source['title'] = fixed_titles
212
            hits.append(input_source)
213

    
214
        pid_types = []
215
        for tag in response.aggs.all_pids.all_types.buckets:
216
            pid_types.append(dict(key=tag.key, count=tag.doc_count))
217

    
218
        datasources = []
219
        for tag in response.aggs.all_datasources.all_names.buckets:
220
            datasources.append(dict(key=tag.key, count=tag.doc_count))
221

    
222
        typologies = []
223
        for tag in response.aggs.typologies.buckets:
224
            typologies.append(dict(key=tag.key, count=tag.doc_count))
225

    
226
        publishers = []
227
        for tag in response.aggs.all_publisher.buckets:
228
            if len(tag.key) > 0:
229
                publishers.append(dict(key=tag.key, count=tag.doc_count))
230

    
231
        return DLIESResponse(total=response.hits.total,
232
                             facet=dict(pid=pid_types, typology=typologies, datasource=datasources,
233
                                        publishers=publishers), hits=hits)
234

    
235
    def related_type(self, object_id, object_type, start=None):
236
        args = {'target.objectType': object_type}
237
        query_type = Q('nested', path='target', query=Q('bool', must=[Q('match', **args)]))
238
        args_id = {'source.dnetIdentifier': object_id}
239
        query_for_id = Q('nested', path='source', query=Q('bool', must=[Q('match', **args_id)]))
240
        s = Search(using=self.client).index(self.index_name).doc_type('scholix').query(query_for_id & query_type)
241
        if start:
242
            s = s[start:start + 10]
243

    
244
        response = s.execute()
245
        hits = []
246

    
247
        for index_hit in response.hits:
248
            current_item = index_hit.__dict__['_d_']
249
            if 'target' in current_item:
250
                ids = []
251
                for item in current_item['target']['identifier']:
252
                    c_it = item
253
                    c_it['url'] = resolveIdentifier(item['identifier'], item['schema'])
254
                    ids .append(c_it)
255
                current_item['target']['identifier'] = ids
256
            hits.append(current_item)
257

    
258
        return hits
259

    
260
    def fix_collectedFrom(self, source, relation):
261
        if relation is None:
262
            return
263
        relSource = relation.get('source')
264
        collectedFrom = relSource['collectedFrom']
265
        for coll in collectedFrom:
266
            for d in source['datasources']:
267
                if d['datasourceName'] == coll['provider']['name']:
268
                    d['provisionMode'] = coll['provisionMode']
269
        return source
270

    
271
    def item_by_id(self, id, type=None, start=None):
272
        try:
273
            res = self.client.get(index=self.index_name, doc_type='object', id=id)
274
            hits = []
275
            input_source = res['_source']
276
            fixed_titles = []
277
            for t in input_source.get('title'):
278
                if len(t) > 0 and t[0] == '"' and t[-1] == '"':
279
                    fixed_titles.append(t[1:-1])
280
                else:
281
                    fixed_titles.append(t)
282
            input_source['title'] = fixed_titles
283

    
284
            for ids in input_source.get('localIdentifier', []):
285
                ds = resolveIdentifier(ids['id'], ids['type'])
286
                ids['url'] = ds
287
            related_publications = []
288
            related_dataset = []
289
            related_unknown = []
290

    
291
            rel_source = None
292
            if input_source.get('relatedPublications') > 0:
293
                if 'publication' == type:
294
                    related_publications = self.related_type(id, 'publication', start)
295
                else:
296
                    related_publications = self.related_type(id, 'publication')
297
                if len(related_publications) > 0:
298
                    rel_source = related_publications[0]
299
                else:
300
                    rel_source = {}
301
            if input_source.get('relatedDatasets') > 0:
302
                if 'dataset' == type:
303
                    related_dataset = self.related_type(id, 'dataset', start)
304
                else:
305
                    related_dataset = self.related_type(id, 'dataset')
306
                rel_source = related_dataset[0]
307
            if input_source.get('relatedUnknown') > 0:
308
                if 'unknown' == type:
309
                    related_unknown = self.related_type(id, 'unknown', start)
310
                else:
311
                    related_unknown = self.related_type(id, 'unknown')
312
                rel_source = related_unknown[0]
313

    
314
            input_source = self.fix_collectedFrom(input_source, rel_source)
315
            hits.append(input_source)
316

    
317
            hits.append(dict(related_publications=related_publications, related_dataset=related_dataset,
318
                             related_unknown=related_unknown))
319

    
320
            return DLIESResponse(total=1, hits=hits)
321
        except Exception as e:
322
            print "Error on getting item "
323
            print e
324
            print "on line %i" % sys.exc_traceback.tb_lineno
325
            return DLIESResponse()
(2-2/2)