Search code examples
pythonescapingcharactersparqldbpedia

How to escape special characters in SPARQL Prefixed Names?


I'm making requests to DBPedia using SPARQL and Python.

Sadly, I'm always getting an error when I send requests with special characters (like parenthesis).

I tried to escape it with backslashes (as in code below) but it's not working.

I read that I could specify the entire URI but it doesn't work either (but I might have not done it the right way).

Does anybody have another option or could provide an example of how I can write my request with the entire URI, considering the request I already have?

query = """
    PREFIX : <http://dbpedia.org/resource/>
    SELECT DISTINCT ?s ?p ?o WHERE {
       {
           ?s ?p ?o
           FILTER (?s=:Grimaldi_\(crater\))

       }
    }
    """

Here is the error I get:

QueryBadFormed: QueryBadFormed: a bad request has been sent to the endpoint, probably the sparql query is bad formed.

Response: b"Virtuoso 37000 Error SP030: SPARQL compiler, line 0: Bad character '\\' (0x5c) in SPARQL expression at '\\'\n\nSPARQL query:\n\n#output-format:application/sparql-results+json\n\n PREFIX : <http://dbpedia.org/resource/>\nSELECT DISTINCT ?s ?p ?o WHERE {\n {\n ?s ?p ?o\n FILTER (?s=:Grimaldi_\\(crater\\))\n\n }\n}\n"


Solution

  • The full URI definitely works, as --

    SELECT DISTINCT ?s ?p ?o WHERE {
       {
           ?s ?p ?o
           FILTER ( ?s = <http://dbpedia.org/resource/Grimaldi_(crater)> )
       }
    }
    

    There is an open bug in Virtuoso v7's handling of Prefixed Names with backslash escaping (such as your :Grimaldi_\(crater\) with PREFIX : <http://dbpedia.org/resource/>, or the more common dbr:Grimaldi_\(crater\) with PREFIX dbr: <http://dbpedia.org/resource/>). Please add your voice to the github issue, to help raise its priority.

    The backslash-escaping in prefixed names now works as it should in Virtuoso 7 (07.20.3230, as of commit 5f68a2e2f2, 2019-04-01), which backs the DBpedia instance.