Search code examples
pythonfiltersparqlrdf

is there a way to parameterize a sparql filter condition?


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.


Solution

  • 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)