Reputation: 45
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?
Upvotes: 1
Views: 836
Reputation: 10213
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)
Upvotes: 3
Reputation: 157
the property rdf:label expects a string at the place of object. You are not putting the object in inverted commas. You should do it like this:
knows_query = """
SELECT ?min ?max
WHERE
{ ?s rdfs:label \""""+x+"""\";
mydb:min ?min ;
mydb:max ?max.
}"""
Now if you will print this query, it will show the following output on the console:
SELECT ?min ?max
WHERE
{ ?s rdfs:label "Inconel_625";
mydb:min ?min ;
mydb:max ?max.
}
Which is what you want and it should work. Let me know if you still don't get it to work. I will be happy to help.
Upvotes: 1