aboutsummaryrefslogtreecommitdiff
path: root/gn3
diff options
context:
space:
mode:
authorMunyoki Kilyungi2024-09-11 13:05:04 +0300
committerJohn Nduli Kilyungi2024-09-18 08:32:34 +0300
commit47859daf988ff05173801f46b997bae759d1c48d (patch)
tree68440647be8b77db81562dde6f4fa00ab3d3f66e /gn3
parent304529f658980687f8a8561f7b71777f0f1af1a5 (diff)
downloadgenenetwork3-47859daf988ff05173801f46b997bae759d1c48d.tar.gz
Rename sparql_construct_query -> sparql_query.
* gn3/db/rdf/__init__.py (sparql_construct_query): Rename to... (sparql_query): ... this. Extend function to be able to return JSQN for SELECT queries. (query_frame_and_compact): Ditto. (query_and_compact): Ditto. (query_and_frame): Ditto. Signed-off-by: Munyoki Kilyungi <me@bonfacemunyoki.com>
Diffstat (limited to 'gn3')
-rw-r--r--gn3/db/rdf/__init__.py17
1 files changed, 11 insertions, 6 deletions
diff --git a/gn3/db/rdf/__init__.py b/gn3/db/rdf/__init__.py
index 94a5776..f0ac494 100644
--- a/gn3/db/rdf/__init__.py
+++ b/gn3/db/rdf/__init__.py
@@ -163,18 +163,23 @@ PHENOTYPE_CONTEXT = (
)
-def sparql_construct_query(query: str, endpoint: str) -> dict:
+def sparql_query(query: str, endpoint: str, format_type="json-ld") -> dict:
"""Query virtuoso using a CONSTRUCT query and return a json-ld
dictionary"""
sparql = SPARQLWrapper(endpoint)
+ if format_type == "json-ld":
+ sparql.setQuery(query)
+ results = sparql.queryAndConvert()
+ return json.loads(results.serialize(format=format_type)) # type: ignore
+ # For SELECTs
+ sparql.setReturnFormat(JSON)
sparql.setQuery(query)
- results = sparql.queryAndConvert()
- return json.loads(results.serialize(format="json-ld")) # type: ignore
+ return sparql.queryAndConvert()["results"]["bindings"] # type: ignore
def query_frame_and_compact(query: str, context: dict, endpoint: str) -> dict:
"""Frame and then compact the results given a context"""
- results = sparql_construct_query(query, endpoint)
+ results = sparql_query(query, endpoint)
return jsonld.compact(
jsonld.frame(results, context), context, options={"graph": True}
)
@@ -182,13 +187,13 @@ def query_frame_and_compact(query: str, context: dict, endpoint: str) -> dict:
def query_and_compact(query: str, context: dict, endpoint: str) -> dict:
"""Compact the results given a context"""
- results = sparql_construct_query(query, endpoint)
+ results = sparql_query(query, endpoint)
return jsonld.compact(results, context, options={"graph": True})
def query_and_frame(query: str, context: dict, endpoint: str) -> dict:
"""Frame the results given a context"""
- results = sparql_construct_query(query, endpoint)
+ results = sparql_query(query, endpoint)
return jsonld.frame(results, context)