Skip to content

Commit 42317d8

Browse files
committed
perf(SPARQL): cache endpoint — 1 COUNT query per fonte invece di 1 per gruppo
dati_camera: 103 gruppi → 1 query (prima 103) dati_cultura: 213 gruppi → 1 query (prima 213) dati_senato: 80 gruppi → 1 query (prima 80) Riduce il tempo SPARQL da minuti a secondi.
1 parent b0379bb commit 42317d8

1 file changed

Lines changed: 25 additions & 18 deletions

File tree

scripts/collectors/sparql.py

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111

1212
logger = logging.getLogger(__name__)
1313

14+
# Cache endpoint→reachable per run. Evita COUNT query per ogni gruppo
15+
# della stessa fonte SPARQL (dati_camera: 103 gruppi → 1 query invece di 103).
16+
_endpoint_cache: dict[str, bool] = {}
17+
1418

1519
def _group_sparql_bindings(bindings: list[dict]) -> dict[str, dict]:
1620
grouped: dict[str, dict] = {}
@@ -114,23 +118,26 @@ def validate_items(items: list[dict]) -> dict[str, Any]:
114118
result["error"] = "No SPARQL endpoint"
115119
return result
116120

117-
# Probe: execute a COUNT query
118-
try:
119-
count_query = f"""
120-
SELECT (COUNT(*) AS ?cnt) WHERE {{
121-
GRAPH <{graph_uri}> {{ ?s ?p ?o }}
122-
}}
123-
""".strip()
124-
bindings = execute_sparql(endpoint, count_query, timeout=15)
125-
if bindings:
126-
cnt = bindings[0].get("cnt", "0")
127-
result["reachable"] = True
128-
result["triple_count"] = int(cnt) if cnt and str(cnt).isdigit() else 0
129-
result["readiness_score"] = 3 # SPARQL reachable e risponde
130-
else:
131-
result["error"] = "Empty response"
132-
except Exception as exc:
133-
result["error"] = str(exc)
134-
result["readiness_score"] = 0
121+
# Cache endpoint: se gia' verificato, usa risultato senza COUNT query
122+
if endpoint not in _endpoint_cache:
123+
try:
124+
count_query = f"""
125+
SELECT (COUNT(*) AS ?cnt) WHERE {{
126+
GRAPH <{graph_uri}> {{ ?s ?p ?o }}
127+
}}
128+
""".strip()
129+
bindings = execute_sparql(endpoint, count_query, timeout=10)
130+
if bindings:
131+
cnt = bindings[0].get("cnt", "0")
132+
_endpoint_cache[endpoint] = True
133+
result["triple_count"] = int(cnt) if cnt and str(cnt).isdigit() else 0
134+
else:
135+
_endpoint_cache[endpoint] = False
136+
except Exception as exc:
137+
_endpoint_cache[endpoint] = False
138+
result["error"] = str(exc)
139+
140+
result["reachable"] = _endpoint_cache.get(endpoint, False)
141+
result["readiness_score"] = 3 if result["reachable"] else 0
135142

136143
return result

0 commit comments

Comments
 (0)