Coverage for ckanext/udc/graph/queries.py: 28%
39 statements
« prev ^ index » next coverage.py v7.7.1, created at 2026-01-19 23:48 +0000
« prev ^ index » next coverage.py v7.7.1, created at 2026-01-19 23:48 +0000
1import logging
2import ckan
3import ckan.plugins.toolkit as tk
4import ckan.plugins as plugins
6from datetime import datetime
7from .sparql_client import SparqlClient
9log = logging.getLogger(__name__)
12def get_client() -> SparqlClient:
13 return plugins.get_plugin('udc').sparql_client
16def get_uri_as_object_usage(object_uri):
17 """Return the number of occurrence when the uri is used as an object."""
18 query = f"""
19 select (count(?s) as ?cnt) where {{
20 ?s ?p <{object_uri}> .
21 }}
22 """
23 client = get_client()
24 result = client.execute_sparql(query)
26 return int(result["results"]["bindings"][0]["cnt"]["value"])
28def get_o_by_sp(s, p):
29 query = f"""
30 select ?o where {{
31 <{s}> <{p}> ?o .
32 }} LIMIT 1"""
33 client = get_client()
34 result = client.execute_sparql(query)
35 if len(result["results"]["bindings"]) > 0:
36 return result["results"]["bindings"][0]["o"]["value"]
37 return None
39def get_num_paths(uri_a: str, uri_b: str):
40 """
41 Find the number of paths from 'uri_a' to 'uri_b'.
42 https://graphdb.ontotext.com/documentation/10.2/graph-path-search.html
43 """
44 query = f"""
45 PREFIX path: <http://www.ontotext.com/path#>
46 PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
48 SELECT ?pathIndex ?edgeIndex ?edge
49 WHERE {{
50 SERVICE path:search {{
51 [] path:findPath path:allPaths ;
52 path:sourceNode <{uri_a}> ;
53 path:destinationNode <{uri_b}> ;
54 path:pathIndex ?pathIndex;
55 path:resultBindingIndex ?edgeIndex ;
56 path:resultBinding ?edge ;
57 }}
58 }}
59 """
60 client = get_client()
61 result = client.execute_sparql(query)
62 # print('num_paths=', len(result["results"]["bindings"]), uri_a, uri_b)
63 # {pathIndex: {edgeIndex: str[]}}
64 results = {}
65 for row in result["results"]["bindings"]:
66 pathIndex = row['pathIndex']['value']
67 edgeIndex = row['edgeIndex']['value']
68 edge = row['edge']['value']
69 # print(edge)
70 s = edge['s']['value']
71 p = edge['p']['value']
72 o = edge['o']['value']
73 if not results.get(pathIndex):
74 results[pathIndex] = {}
76 results[pathIndex][edgeIndex] = [s, p, o]
78 # Reformat it into {pathIndex: str[][]}
79 for pathIndex in results:
80 results[pathIndex] = [v for k, v in sorted(results[pathIndex].items())]
82 return results