簡體   English   中英

有沒有辦法參數化 sparql 過濾條件?

[英]is there a way to parameterize a sparql filter condition?

我正在嘗試找出以浮點值作為輸入來參數化過濾條件的最佳方法。

count=25.67
FILTER(?price < count)

代替:

FILTER ( ?price < 25.67 )

“count”的值將作為輸入。

我想知道在 FILTER 命令中包含 object 計數的語法。

先感謝您。

沒有神奇的 SPARQL 語法可以做到這一點:就像 SQL 一樣,您必須使用字符串進行 SPARQL 查詢,至少在 Python 中是這樣。 因此,您想要的任何用戶輸入都必須將字符串作為查詢發送。 假設您想獲得所有價格高於price_to_be_less_than ,您可以在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

我使用.format() ,而不是 f-strings (個人口味),所以我必須在查詢中使用雙括號“{{”

下面是一個使用setQuery的示例,其中使用了通過 `.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"))

(改編自 https ://sparqlwrapper.readthedocs.io/en/latest/main.html的 SPARQLWrapper 文檔)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM