Skip to content

search

LocalSearchService

Bases: SearchService

Source code in datasets/services/search.py
 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
class LocalSearchService(SearchService):
    index_path: Path

    def __init__(self, index_path: Path):
        self.index_path = index_path

    def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
        url = parse_int_or_none(options.get('url', None))
        min_count = parse_int_or_none(options.get('min_count', None))
        max_count = parse_int_or_none(options.get('max_count', None))

        result_data = BoldCli.search(self.index_path, query, limit, offset, pos.to_int(), url, min_count, max_count)
        return SearchResult(
            count=result_data['count'],
            hits=[
                SearchHit(
                    score=hit['score'],
                    document=self._parse_doc(hit['doc'])
                )
                for hit in result_data['hits']
            ],
            agg=result_data['agg']
        )

    def _parse_doc(self, doc: dict) -> TermDocument:
        doc = {k: v[0] for k, v in doc.items()}

        iri = doc['iri']
        type = 'uri' if 'http' in iri else 'literal'
        lang = None
        if type == 'literal' and re.match(r'^.*@[a-z]*$', iri):
            iri, lang = iri.rsplit('@', 1)

        return TermDocument(
            type=type,
            value=iri.removeprefix('<').removesuffix('>'),
            lang=lang,
            pos=TermPos.from_int(doc.get('pos', 0)),
            rdf_type=doc.get('ty', None),
            label=doc.get('label', None),
            count=doc.get('count', None),
            search_text=doc.get('iri_text', None),
            description=doc.get('description', None),
        )

index_path = index_path instance-attribute

__init__(index_path)

Source code in datasets/services/search.py
94
95
def __init__(self, index_path: Path):
    self.index_path = index_path

search(query, pos, limit=100, offset=0, timeout=5000, **options)

Source code in datasets/services/search.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
    url = parse_int_or_none(options.get('url', None))
    min_count = parse_int_or_none(options.get('min_count', None))
    max_count = parse_int_or_none(options.get('max_count', None))

    result_data = BoldCli.search(self.index_path, query, limit, offset, pos.to_int(), url, min_count, max_count)
    return SearchResult(
        count=result_data['count'],
        hits=[
            SearchHit(
                score=hit['score'],
                document=self._parse_doc(hit['doc'])
            )
            for hit in result_data['hits']
        ],
        agg=result_data['agg']
    )

SearchHit dataclass

Bases: Serializable

Source code in datasets/services/search.py
65
66
67
68
@dataclass
class SearchHit(Serializable):
    score: float
    document: Serializable | TermDocument

document: Serializable | TermDocument class-attribute

score: float class-attribute

SearchResult dataclass

Bases: Serializable

Source code in datasets/services/search.py
71
72
73
74
75
76
@dataclass
class SearchResult(Serializable):
    count: int = field(default=0)
    hits: List[SearchHit | dict] = field(default_factory=list)
    agg: dict = field(default_factory=dict)
    error: Optional[str] = None

agg: dict = field(default_factory=dict) class-attribute

count: int = field(default=0) class-attribute

error: Optional[str] = None class-attribute

hits: List[SearchHit | dict] = field(default_factory=list) class-attribute

SearchService

Bases: ABC

Source code in datasets/services/search.py
79
80
81
82
class SearchService(ABC):
    @abstractmethod
    def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
        pass

search(query, pos, limit=100, offset=0, timeout=5000, **options) abstractmethod

Source code in datasets/services/search.py
80
81
82
@abstractmethod
def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
    pass

TermDocument dataclass

Bases: Serializable

Source code in datasets/services/search.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass
class TermDocument(Serializable):
    type: str
    search_text: str
    value: str
    pos: TermPos
    lang: Optional[str] = None
    rdf_type: Optional[str] = None
    label: Optional[str] = None
    description: Optional[str] = None
    count: Optional[int] = None
    range: Optional[str] = None

    def searchable_text(self):
        return ' '.join([
            self.search_text,
            self.label or '',
            self.description or '',
            self.value or '',
        ])

count: Optional[int] = None class-attribute

description: Optional[str] = None class-attribute

label: Optional[str] = None class-attribute

lang: Optional[str] = None class-attribute

pos: TermPos class-attribute

range: Optional[str] = None class-attribute

rdf_type: Optional[str] = None class-attribute

search_text: str class-attribute

type: str class-attribute

value: str class-attribute

searchable_text()

Source code in datasets/services/search.py
56
57
58
59
60
61
62
def searchable_text(self):
    return ' '.join([
        self.search_text,
        self.label or '',
        self.description or '',
        self.value or '',
    ])

TermPos

Bases: Enum

Source code in datasets/services/search.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class TermPos(Enum):
    SUBJECT = 'SUBJECT'
    PREDICATE = 'PREDICATE'
    OBJECT = 'OBJECT'

    def to_int(self):
        match self:
            case TermPos.SUBJECT:
                return 0
            case TermPos.PREDICATE:
                return 1
            case TermPos.OBJECT:
                return 2

    @staticmethod
    def from_int(value: int):
        match value:
            case 0:
                return TermPos.SUBJECT
            case 1:
                return TermPos.PREDICATE
            case 2:
                return TermPos.OBJECT

OBJECT = 'OBJECT' class-attribute

PREDICATE = 'PREDICATE' class-attribute

SUBJECT = 'SUBJECT' class-attribute

from_int(value) staticmethod

Source code in datasets/services/search.py
32
33
34
35
36
37
38
39
40
@staticmethod
def from_int(value: int):
    match value:
        case 0:
            return TermPos.SUBJECT
        case 1:
            return TermPos.PREDICATE
        case 2:
            return TermPos.OBJECT

to_int()

Source code in datasets/services/search.py
23
24
25
26
27
28
29
30
def to_int(self):
    match self:
        case TermPos.SUBJECT:
            return 0
        case TermPos.PREDICATE:
            return 1
        case TermPos.OBJECT:
            return 2

TriplyDBSearchService

Bases: SearchService

Source code in datasets/services/search.py
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
class TriplyDBSearchService(SearchService):
    namespace: str

    def __init__(self, namespace: str):
        self.namespace = namespace

    def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
        endpoint = self.get_endpoint()
        if not endpoint:
            raise ValidationError('Search endpoint is not reachable')

        query = self.build_query(query, pos, limit, offset)
        response = requests.post(
            endpoint,
            data=json.dumps(query),
            timeout=timeout,
            headers={
                'User-Agent': 'https://github.com/EgorDm/BOLD',
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
        )

        if response.status_code != 200:
            return SearchResult(error=response.text)

        result_data = response.json()
        print(result_data)
        return SearchResult(
            count=result_data['hits']['total']['value'],
            hits=[
                SearchHit(
                    score=hit['_score'],
                    document=self._parse_doc(hit['_source'])
                )
                for hit in result_data['hits']['hits']
            ],
        )

    # noinspection PyTypeChecker
    def build_query(self, query, pos: TermPos, limit: int = 100, offset: int = 0):
        base_query = {
            'size': limit,
            'from': offset,
            'query': {"bool": defaultdict(dict)},
        }

        if pos != TermPos.PREDICATE:
            base_query['query']['bool']['must_not'] = [{
                "terms": {
                    "http://www w3 org/1999/02/22-rdf-syntax-ns#type":
                        ["http://www.w3.org/2002/07/owl#DatatypeProperty"]
                }
            }]

        if query:
            base_query['query']['bool']['must'] = [{
                "simple_query_string": {
                    "query": query
                }
            }]
            base_query['query']['bool']['should'] = [{
                "simple_query_string": {
                    "query": query,
                    "fields": [
                        "http://www w3 org/2000/01/rdf-schema#label"
                    ]
                }
            }]

        if pos == TermPos.PREDICATE:
            base_query['query']['bool']['must'] = [
                *base_query['query']['bool'].get('must', []),
                {
                    "match": {
                        "http://www w3 org/1999/02/22-rdf-syntax-ns#type":
                            "http://www.w3.org/2002/07/owl#DatatypeProperty"
                    }
                }
            ]

        return base_query

    def get_endpoint(self):
        response = requests.get(
            f'https://api.triplydb.com/datasets/{self.namespace}/services/',
            timeout=5,
            headers={
                'User-Agent': 'https://github.com/EgorDm/BOLD',
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
        )

        if response.status_code != 200:
            return None

        result_data = response.json()
        for service in result_data:
            if service.get('type', None) == 'elasticSearch':
                return service['endpoint']

        return None

    def _parse_doc(self, doc: dict) -> TermDocument:
        iri = doc['@id']
        rdf_type = doc.get('http://www w3 org/1999/02/22-rdf-syntax-ns#type', None)
        pos = TermPos.PREDICATE if rdf_type == 'http://www.w3.org/2002/07/owl#DatatypeProperty' \
            else (TermPos.SUBJECT if 'http' in iri else TermPos.OBJECT)

        label = doc.get('http://www w3 org/2000/01/rdf-schema#label', None)
        search_text = label if label else re.sub(r'[-_#]', ' ', iri.split('/')[-1].split('#')[-1])

        return TermDocument(
            type='uri',
            value=doc['@id'],
            pos=pos,
            rdf_type=first_or_self(rdf_type),
            label=first_or_self(label),
            description=first_or_self(doc.get('http://www w3 org/2000/01/rdf-schema#comment', None)),
            count=None,
            search_text=first_or_self(search_text),
            range=doc.get('http://www w3 org/2000/01/rdf-schema#range', None),
        )

namespace = namespace instance-attribute

__init__(namespace)

Source code in datasets/services/search.py
198
199
def __init__(self, namespace: str):
    self.namespace = namespace

build_query(query, pos, limit=100, offset=0)

Source code in datasets/services/search.py
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
def build_query(self, query, pos: TermPos, limit: int = 100, offset: int = 0):
    base_query = {
        'size': limit,
        'from': offset,
        'query': {"bool": defaultdict(dict)},
    }

    if pos != TermPos.PREDICATE:
        base_query['query']['bool']['must_not'] = [{
            "terms": {
                "http://www w3 org/1999/02/22-rdf-syntax-ns#type":
                    ["http://www.w3.org/2002/07/owl#DatatypeProperty"]
            }
        }]

    if query:
        base_query['query']['bool']['must'] = [{
            "simple_query_string": {
                "query": query
            }
        }]
        base_query['query']['bool']['should'] = [{
            "simple_query_string": {
                "query": query,
                "fields": [
                    "http://www w3 org/2000/01/rdf-schema#label"
                ]
            }
        }]

    if pos == TermPos.PREDICATE:
        base_query['query']['bool']['must'] = [
            *base_query['query']['bool'].get('must', []),
            {
                "match": {
                    "http://www w3 org/1999/02/22-rdf-syntax-ns#type":
                        "http://www.w3.org/2002/07/owl#DatatypeProperty"
                }
            }
        ]

    return base_query

get_endpoint()

Source code in datasets/services/search.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def get_endpoint(self):
    response = requests.get(
        f'https://api.triplydb.com/datasets/{self.namespace}/services/',
        timeout=5,
        headers={
            'User-Agent': 'https://github.com/EgorDm/BOLD',
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
    )

    if response.status_code != 200:
        return None

    result_data = response.json()
    for service in result_data:
        if service.get('type', None) == 'elasticSearch':
            return service['endpoint']

    return None

search(query, pos, limit=100, offset=0, timeout=5000, **options)

Source code in datasets/services/search.py
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
def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
    endpoint = self.get_endpoint()
    if not endpoint:
        raise ValidationError('Search endpoint is not reachable')

    query = self.build_query(query, pos, limit, offset)
    response = requests.post(
        endpoint,
        data=json.dumps(query),
        timeout=timeout,
        headers={
            'User-Agent': 'https://github.com/EgorDm/BOLD',
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
    )

    if response.status_code != 200:
        return SearchResult(error=response.text)

    result_data = response.json()
    print(result_data)
    return SearchResult(
        count=result_data['hits']['total']['value'],
        hits=[
            SearchHit(
                score=hit['_score'],
                document=self._parse_doc(hit['_source'])
            )
            for hit in result_data['hits']['hits']
        ],
    )

WikidataSearchService

Bases: SearchService

Source code in datasets/services/search.py
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
class WikidataSearchService(SearchService):
    def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
        type = 'item'
        if pos == TermPos.PREDICATE:
            type = 'property'

        response = requests.get(
            'https://www.wikidata.org/w/api.php',
            params={
                'action': 'wbsearchentities',
                'search': query,
                'language': 'en',
                'uselang': 'en',
                'type': type,
                'format': 'json',
                'formatversion': 2,
                'errorformat': 'plaintext',
                'limit': limit,
                'continue': offset,
            },
            timeout=timeout,
            headers={
                'User-Agent': 'https://github.com/EgorDm/BOLD',
            }
        )

        if response.status_code != 200:
            return SearchResult(error=response.text)

        result_data = response.json()
        return SearchResult(
            count=999999 if 'search-continue' in result_data else offset + len(result_data.get('search', [])),
            hits=[
                SearchHit(
                    score=1.0,
                    document=self._parse_doc(hit, pos),
                )
                for hit in result_data.get('search', [])
            ],
        )

    def _parse_doc(self, doc: dict, pos: TermPos) -> TermDocument:
        iri = doc['concepturi']
        if pos == TermPos.PREDICATE:
            iri = f'http://www.wikidata.org/prop/direct/{doc["id"]}'

        return TermDocument(
            type='uri',
            value=iri,
            pos=pos,
            rdf_type=None,
            label=doc.get('label', None),
            description=doc.get('description', None),
            count=doc.get('count', None),
            search_text=doc.get('label', None),
        )

search(query, pos, limit=100, offset=0, timeout=5000, **options)

Source code in datasets/services/search.py
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
def search(self, query, pos: TermPos, limit: int = 100, offset: int = 0, timeout=5000, **options) -> SearchResult:
    type = 'item'
    if pos == TermPos.PREDICATE:
        type = 'property'

    response = requests.get(
        'https://www.wikidata.org/w/api.php',
        params={
            'action': 'wbsearchentities',
            'search': query,
            'language': 'en',
            'uselang': 'en',
            'type': type,
            'format': 'json',
            'formatversion': 2,
            'errorformat': 'plaintext',
            'limit': limit,
            'continue': offset,
        },
        timeout=timeout,
        headers={
            'User-Agent': 'https://github.com/EgorDm/BOLD',
        }
    )

    if response.status_code != 200:
        return SearchResult(error=response.text)

    result_data = response.json()
    return SearchResult(
        count=999999 if 'search-continue' in result_data else offset + len(result_data.get('search', [])),
        hits=[
            SearchHit(
                score=1.0,
                document=self._parse_doc(hit, pos),
            )
            for hit in result_data.get('search', [])
        ],
    )

first_or_self(item)

Source code in datasets/services/search.py
321
322
323
324
325
def first_or_self(item: Union[List[Any], Any]):
    if isinstance(item, list):
        return item[0]

    return item

merge_results(a, b, query)

Source code in datasets/services/search.py
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
def merge_results(
    a: SearchResult,
    b: SearchResult,
    query: str,
) -> SearchResult:
    score_fn = lambda x: fuzz.partial_ratio(x.document.searchable_text(), query)
    a_hits = deque((score_fn(hit), hit) for hit in a.hits)
    b_hits = deque((score_fn(hit), hit) for hit in b.hits)

    seen = set()
    hits = []
    while a_hits and b_hits:
        if a_hits[0][0] > b_hits[0][0]:
            item = a_hits.popleft()[1]
        else:
            item = b_hits.popleft()[1]

        if item.document.value not in seen:
            hits.append(item)
            seen.add(item.document.value)

    for (_, item) in a_hits + b_hits:
        if item.document.value not in seen:
            hits.append(item)
            seen.add(item.document.value)

    return SearchResult(
        count=len(hits),
        hits=hits,
    )

parse_int_or_none(value)

Source code in datasets/services/search.py
85
86
87
88
def parse_int_or_none(value: str) -> int:
    if value is None:
        return None
    return int(value)