Search code examples
sparqlrdfsrdflib

Parametrized SPARQL Queries with python RDFLib


I am trying to query a very simple database about Alloys with a parametrized SPARQL query using RDFLib:

x = "Inconel_625"

g = Graph()
g.parse ("Desktop/materials.ttl")


knows_query = """
SELECT ?min ?max
WHERE
{ ?s rdfs:label  """+x+""";
 mydb:min ?min ;
 mydb:max ?max.
}"""

qres = g.query(knows_query)
for x in qres:
    print(x.min, x.max)

Unfortunatly this code does not work. If i replace """+x+""" with "Inconel_625 it works somehow. What am i not seeing? Is it not possible to parametrize a sparql query in RDFLib?


Solution

  • Yes, rdflib supports parameterized queries by allowing one to bind values to variables via the initBindings keyword argument to Graph.query().

    Here is your example code modified to use it:

    from rdflib import Graph, Literal
    
    label = "Inconel_625"
    
    g = Graph()
    g.parse("Desktop/materials.ttl")
    
    knows_query = """
    SELECT ?min ?max
    WHERE
    { ?s rdfs:label ?label ;
     mydb:min ?min ;
     mydb:max ?max .
    }"""
    
    qres = g.query(knows_query, initBindings={"label": Literal(label)})
    for x in qres:
        print(x.min, x.max)