2

The following code should return a dictionary of the subject of all triples in the ontology. It, instead, returns the entire ontology as an XML string.

from SPARQLWrapper import SPARQLWrapper, JSON

sparql = SPARQLWrapper("http://purl.org/sudo/ontology/sudo.owl")
sparql.setQuery("""
    SELECT ?subject
    WHERE {?subject ?verb  ?object}
    """)

sparql.setReturnFormat(JSON)
results = sparql.query().convert()
print results.keys()

The above code works fine with a different ontology, which suggests that the ontology is the issue. I'm not sure what the issue with the ontology could be. I generated the ontology with Protege, it can load into vOWL, and it passes vOWL's ontology validation.

Stanislav Kralin
  • 11,070
  • 4
  • 35
  • 58
mac389
  • 3,004
  • 5
  • 38
  • 62
  • 1
    Can you share the ontology? – Ignazio Mar 05 '18 at 06:44
  • @Ignazio I thought it's the one in the example? – UninformedUser Mar 05 '18 at 07:48
  • 1
    mac389, are you sure that `SOARQLWrapper` accepts remote RDF file path as an argument? AFAIK, this should be SPARQL endpoint address (which ends with `sparql` in most cases). If you want to query RDF file, perhaps you should load it into local store, possibly using [tag:rdflib]. – Stanislav Kralin Mar 05 '18 at 08:10
  • Stanislav is right, even the first sentence makes this clear: *"This is a wrapper around a SPARQL service"* there is no built-in triple store, it's just a wrapper for the SPARQL HTTP protocol – UninformedUser Mar 05 '18 at 16:35

1 Answers1

3

SPARQLWrapper()'s first argument should be a SPARQL endpoint address:

  • can't perform SPARQL queries against RDF files.
  • if you want to query against an RDF file, you should load it into a local store using .
from rdflib import Graph

g = Graph()
g.parse("http://purl.org/sudo/ontology/sudo.owl", format="xml")

qres = g.query("""
    SELECT DISTINCT ?s {
        ?s ?p ?o
    }""")

for row in qres:
    print("%s" % row)

If you really need SPARQL query results in JSON format (spec):

import sys
from rdflib import Graph
from rdflib.plugins.sparql.results.jsonresults import JSONResultSerializer

g = Graph()
g.parse("http://purl.org/sudo/ontology/sudo.owl", format="xml")

qres = g.query("""
    SELECT DISTINCT ?s {
        ?s ?p ?o
    }""")

JSONResultSerializer(qres).serialize(sys.stdout)

If you wish to abstract from RDF serialization, you should use .

Stanislav Kralin
  • 11,070
  • 4
  • 35
  • 58
  • owlready would be a good option, but it requires Python 3. I'm stuck with 2.7 for this project. – mac389 Mar 06 '18 at 15:51