-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal_query_executor.py
52 lines (45 loc) · 1.85 KB
/
local_query_executor.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
# basic imports
import pprint
import logging
import logging_config as lc
# graph imports
import rdflib
from rdflib.util import from_n3
from rdflib import RDF, Graph, Namespace, URIRef, Literal
# enable logging
logger = logging.getLogger(__name__)
logger.setLevel(lc.LOG_LEVEL)
####################################
# QUERY EXECUTION FUNCTIONS #
####################################
def executeQuery(graph: Graph, query: str) -> dict:
# run the original query on the graph to get the results
result = graph.query(query)
logger.debug(f'Result of the query when executed on the local graph {result.bindings}')
logger.debug(f'Variables used in the result of the query {result.vars}')
# reformat the result into a SPARQL 1.1 JSON result structure
json_result = reformatResultIntoSPARQLJson(result)
# unregister the ASK knowledge interaction for the knowledge base
return json_result
def reformatResultIntoSPARQLJson(result:dict) -> dict:
json_result = {
"head" : { "vars": [str(var) for var in result.vars]
},
"results": {
"bindings": []
}
}
if result.bindings != []:
bindings = []
for binding in result.bindings:
b = {}
for key in binding:
if isinstance(binding[key],rdflib.term.Literal):
b[str(key)] = {"type": "literal", "datatype": str(binding[key].datatype), "value": str(binding[key])}
if binding[key].datatype == None:
b[str(key)]["datatype"] = "http://www.w3.org/2001/XMLSchema#string"
if isinstance(binding[key],rdflib.term.URIRef):
b[str(key)] = {"type": "uri", "value": str(binding[key])}
bindings.append(b)
json_result["results"] = {"bindings": bindings}
return json_result