How to add external variables to a SPARQL query?

107 Views Asked by At

I have the following codes:

name = [str(s) for s,  in graph.query('''
    SELECT ?lbl 
    WHERE {
        <http://www.wikidata.org/entity/Q59692464> <http://www.wikidata.org/prop/direct/P1657> ?obj .
        ?obj rdfs:label ?lbl .
    }
    ''')]

I want to pass the two values<http://www.wikidata.org/entity/Q59692464>and <http://www.wikidata.org/prop/direct/P1657> as variables ?mov and ?rel.

I tried to use %s but got an error:

name = [str(s) for s,  in graph.query('''
    SELECT ?lbl 
    WHERE {
        <'%s'> <http://www.wikidata.org/prop/direct/P1657> ?obj .
        ?obj rdfs:label ?lbl .
    }
    '''%mov)]
TypeError: unsupported operand type(s) for %: 'SPARQLResult' and 'str'

What I want is something like this:

name = [str(s) for s,  in graph.query('''
    SELECT ?lbl 
    WHERE {
        ?mov ?rel ?obj .
        ?obj rdfs:label ?lbl .
    }
    ''')]

Thanks a lot for your help!

2

There are 2 best solutions below

0
HES On

You can try using double curly braces and the .format method. See:

name = [str(s) for s in graph.query('''
    SELECT ?lbl 
    WHERE {{
        {} {} ?obj .
        ?obj rdfs:label ?lbl .
    }}
    '''.format("<http://www.wikidata.org/entity/Q59692464>", "<http://www.wikidata.org/prop/direct/P1657>"))]

I would probably break this up and format the query as a string, and then call graph.query():

skeleton_query = '''
    SELECT ?lbl 
    WHERE {{
        {} {} ?obj .
        ?obj rdfs:label ?lbl .
    }}
    '''

formatted_query = skeleton_query.format("<http://www.wikidata.org/entity/Q59692464>", "<http://www.wikidata.org/prop/direct/P1657>")

result = graph.query(formatted_query)

0
rodentrabies On

Assuming you use rdflib, you can do something like this:

mov = rdflib.URIRef("http://www.wikidata.org/entity/Q59692464")
rel = rdflib.URIRef("http://www.wikidata.org/prop/direct/P1657")

name = [str(s) for s, in graph.query('''
SELECT ?lbl 
WHERE {
  ?mov ?rel ?obj .
  ?obj rdfs:label ?lbl .
}
''', initBindings={'mov': mov, 'rel': rel})]