This repository was archived by the owner on Oct 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch.py
More file actions
49 lines (37 loc) · 1.39 KB
/
search.py
File metadata and controls
49 lines (37 loc) · 1.39 KB
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
#!/usr/bin/env python
import os
import whoosh.fields
import whoosh.qparser
import whoosh.index
class RDFSearch(object):
""" creates a whoosh index on a graph """
def __init__(self, index_dir, graph=None):
self.index_dir = index_dir
self.schema = whoosh.fields.Schema(
uri=whoosh.fields.ID(stored=True), body=whoosh.fields.TEXT
)
self.index = None
if os.path.exists(self.index_dir):
self.index = whoosh.index.open_dir(self.index_dir)
if self.index is None:
os.makedirs(self.index_dir)
self.index = whoosh.index.create_in(self.index_dir, self.schema)
if graph is not None:
self.index_graph(graph)
self.searcher = self.index.searcher()
self.term_parser = whoosh.qparser.MultifieldParser(
["uri", "body"], schema=self.schema, group=whoosh.qparser.OrGroup
)
def index_graph(self, graph):
""" takes a graph to be indexed """
writer = self.index.writer()
for (s, p, o) in graph.triples((None, None, None)):
uri = "%s" % s
body = "%s" % o
writer.add_document(uri=uri, body=body)
writer.commit()
def search(self, term):
results = self.searcher.search(self.term_parser.parse(term))
return [r["uri"] for r in results]
def close(self):
self.searcher.close()