2

With rdflib's Graph.query, is there a way to pass in a list of values to use in a SPARQL query? I'm aware of the initBindings argument for binding single values to variables, but I'm looking to pass in the equivalent of a VALUES block.

Conceptually, something like this:

from rdflib import Graph, URIRef

g = Graph()

query = """
    PREFIX wikibase: <http://wikiba.se/ontology#>
    PREFIX wd: <http://www.wikidata.org/entity/>
    PREFIX wdt: <http://www.wikidata.org/prop/direct/>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
    
    SELECT ?org ?label ?altLabel
    WHERE {
        SERVICE <https://query.wikidata.org/sparql> {
            ?org rdfs:label ?label filter (lang(?label) = "en") .
            OPTIONAL {
              ?org skos:altLabel ?altLabel filter (lang(?altLabel) = "en") .
            }
            VALUES (?org) { ?values }
        }
    }
"""

values = (
    (URIRef("http://www.wikidata.org/entity/Q533617"),),
    (URIRef("http://www.wikidata.org/entity/Q706184"),),
)

# Something like initBindings, but for list of values?
res = g.query(query, values=values)  
King Chung Huang
  • 5,026
  • 28
  • 24
  • Why not just perform multiple querys? – kpie Jan 31 '22 at 18:10
  • Well, I don't want to hit Wikidata n-times for n-subjects! At the moment, I'm simply filling what I want in the text of the query. But, I'm thinking there must be a proper way to pass in the values like how initBindings works. – King Chung Huang Jan 31 '22 at 18:13
  • To the best of my knowledge hitting wikipedia n-times for n-subjects is the proper way to go. – kpie Jan 31 '22 at 18:24
  • if there is no such function for a prepared query, you can still use Python string manipulation and interpolate the string for the `?values` variable – UninformedUser Jan 31 '22 at 20:07
  • Feel free to contribute back a list expander capability in RDFLib's `initBindings`! – Nicholas Car Feb 17 '22 at 06:40

0 Answers0