问题
I am trying to find out what is the best way to parameterize a filter condition with a float value taken as input.
count=25.67
FILTER(?price < count)
instead of:
FILTER ( ?price < 25.67 )
The value of "count" will be taken as input.
I would like to know the syntax for including the object count in the FILTER command.
Thank you in advance.
回答1:
Here's an example of setQuery
use with a parameter added via `.format():
from SPARQLWrapper import SPARQLWrapper, JSON
def query_dbpedia(my_uri)
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
q = """
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?label
WHERE {{
{} rdfs:label ?label .
}}
""".format(my_uri)
sparql.setQuery(q)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
results_to_return = []
for result in results["results"]["bindings"]:
results_to_return.append(result["label"]["value"])
return results_to_return
print(query_dbpedia("http://dbpedia.org/resource/Asturias"))
(adapted from SPARQLWrapper documentation at https://sparqlwrapper.readthedocs.io/en/latest/main.html)
回答2:
There is no magic SPARQL syntax to do this: like SQL, you have to make a SPARQL query out of a string, at least in Python. Therefore, any user input you want has to make the string that you then send as the query. Say you wanted to get all prices greater than price_to_be_less_than
, you would do this in RDFlib Python:
def get_prices(g, price_to_be_less_than):
q = """
SELECT ?item
WHERE {{
?item ex:hasPrice ?price .
FILTER (?price < {})
}}
""".format(price_to_be_less_than)
items = []
for r in g.query(q):
items.append(r["item"])
return items
I use .format()
, not f-strings (personal taste), so I then have to use double braces, "{{", in the query
来源:https://stackoverflow.com/questions/61616643/is-there-a-way-to-parameterize-a-sparql-filter-condition