Search code examples
pythonsparqlsparqlwrapper

How to add special categories in sparqlwrapper in python


I am using the following sparql query using sparqlwrapper as follows.

from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper("http://live.dbpedia.org/sparql")
sparql.setReturnFormat(JSON)
my_category = 'dbc:Meteorological_concepts'
sparql.setQuery(f" ASK {{ {my_category}  skos:broader{{1,3}} dbc:Medicine }} ")
results = sparql.query().convert()
print(results['boolean'])

As mentioned above it works fine with categories that do not have brackets (e.g., dbc:Meteorological_concepts). However, when I enter a category with brackets (i.e my_category = dbc:Elasticity_(physics)) I get the following error.

b"Virtuoso 37000 Error SP030: SPARQL compiler, line 4: syntax error at 'physics' before ')'\n\nSPARQL query:\ndefine sql:big-data-const 0 \n#output-format:application/sparql-results+json\n\n    ASK { dbc:Elasticity_(physics) skos:broader{1,3} dbc:Medicine }\n"
CRITICAL: Exiting due to uncaught exception <class 'SPARQLWrapper.SPARQLExceptions.QueryBadFormed'>

Is there a way to resolve this issue.

I am happy to provide more details if needed.


Solution

  • I am rewriting what @StanislavKralin mentioned in the above comment. I always try to use full URL in the SPARQL code, particularly when there is special character in SPARQL query.

    from SPARQLWrapper import SPARQLWrapper, JSON
    sparql = SPARQLWrapper("http://live.dbpedia.org/sparql")
    sparql.setReturnFormat(JSON)
    my_category = '<http://dbpedia.org/resource/Category:Elasticity_(physics)>'
    sparql.setQuery(f" ASK {{ {my_category}  skos:broader{{1,3}} dbc:Medicine }} ")
    results = sparql.query().convert()
    print(results['boolean'])