1

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?

grizzli11
  • 45
  • 1
  • 5

2 Answers2

3

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)
Jukka Matilainen
  • 9,608
  • 1
  • 25
  • 19
  • This is a better answer! Also consider the modern Pythonic f-strings! Just have to escape SPARQL's { by using double, e.g. {{, and then you can use variables in an f-string quoted SPARQL query. – Nicholas Car Jun 28 '22 at 11:50
1

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.