-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_classes.py
More file actions
executable file
·95 lines (78 loc) · 3.06 KB
/
query_classes.py
File metadata and controls
executable file
·95 lines (78 loc) · 3.06 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
"""
Simple script to query all classes in the ontology using SPARQL.
This script connects to the Virtuoso SPARQL endpoint and retrieves a list of all classes.
"""
import sys
import time
import requests
from SPARQLWrapper import SPARQLWrapper, JSON
#endpoint_url = "http://localhost:8890/sparql/"
endpoint_url = "http://localhost:88/virtuoso/"
# endpoint_url = "http://10.74.250.168:88/virtuoso/"
def check_endpoint_availability(endpoint_url=endpoint_url, max_retries=3):
"""Check if the SPARQL endpoint is available."""
print(f"Checking if SPARQL endpoint is available...")
for i in range(max_retries):
try:
response = requests.get(endpoint_url)
if response.status_code == 200:
print(f"SPARQL endpoint is available!")
return True
else:
print(f"Attempt {i+1}/{max_retries}: Endpoint returned status code {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Attempt {i+1}/{max_retries}: Connection error: {e}")
if i < max_retries - 1:
print(f"Retrying in 3 seconds...")
time.sleep(3)
print(f"SPARQL endpoint is not available after {max_retries} attempts.")
return False
def query_ontology_classes(endpoint_url):
"""Query all classes in the ontology using SPARQL."""
# Initialize the SPARQL wrapper
sparql = SPARQLWrapper(endpoint_url)
sparql.setReturnFormat(JSON)
# Simple query to get all classes
query = """
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT DISTINCT ?class
WHERE {
?class rdf:type owl:Class .
}
ORDER BY ?class
"""
# Execute the query
try:
print("Querying for owl:Class instances...")
sparql.setQuery(query)
results = sparql.query().convert()
# Extract class URIs from results
classes = []
for result in results["results"]["bindings"]:
classes.append(result["class"]["value"])
return classes
except Exception as e:
print(f"Error executing SPARQL query: {e}")
return []
def main():
"""Main function to execute the query and display results."""
if not check_endpoint_availability():
print("Cannot connect to SPARQL endpoint. Make sure the Virtuoso server is running.")
sys.exit(1)
classes = query_ontology_classes(endpoint_url)
if classes:
print(f"\nFound {len(classes)} classes. Printing first 10:")
for i, class_uri in enumerate(classes[:10], 1):
print(f"{i}. {class_uri}")
else:
print("No classes found or error occurred.")
print("Possible issues:")
print("1. The ontology file might not be properly loaded")
print("2. The ontology might not contain any owl:Class declarations")
print("\nTry running: docker compose logs virtuoso")
if __name__ == "__main__":
main()
if __name__ == "__main__":
main()