2017-01-24 260 views
0

我有一個python腳本,它使用2個SPARQL查詢查詢DBpedia,並且對於每個查詢,將結果放入一個列表中。然後我製作一組這個清單來刪除重複項,並且我得到了我需要的結果。這似乎是一種低效率的方式,如果有可能結合查詢來加速這個過程。結合2個查詢的結果

有人可以通過 SQL SPARQL幫助我結合這些查詢來加速我的Python腳本嗎?

對於上下文:我希望爲該函數(查詢1)的查詢詞的DBpedia頁面的所有屬性的屬性和值的標籤名稱以及具有數字/文本值而不是標籤作爲值(查詢2)。

def querydbpedia(queryword): 
mylist = list() 
sparql = SPARQLWrapper("http://dbpedia.org/sparql") 
sparql.setQuery(""" 
    prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> 

    SELECT DISTINCT ?pLabel ?oLabel ?o WHERE { 
    <http://dbpedia.org/resource/""" + queryword + """> ?p ?o. 
    ?p rdfs:label ?pLabel . 
    ?o rdfs:label ?oLabel . 
    FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en")) 
    FILTER(LANG(?oLabel) = "" || LANGMATCHES(LANG(?oLabel), "en")) 
    } 
""") 

sparql.setReturnFormat(JSON) 
results = sparql.query().convert() 

for result in results["results"]["bindings"]: 
    mystr = (result["pLabel"]["value"] + " - " + result["oLabel"]["value"]).lower() 
    mylist.append(mystr) 

sparql.setQuery(""" 
    prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> 

    SELECT DISTINCT ?pLabel ?oLabel ?o WHERE { 
    <http://dbpedia.org/resource/""" + queryword + """> ?p ?o. 
    ?p rdfs:label ?pLabel . 
    OPTIONAL {?o rdfs:label ?oLabel} . 
    FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en")) 
    FILTER(LANG(?o) = "" || LANGMATCHES(LANG(?o), "en")) 
    } 
""") 

sparql.setReturnFormat(JSON) 
results = sparql.query().convert() 

for result in results["results"]["bindings"]: 
    mystr = (result["pLabel"]["value"] + " - " + result["o"]["value"]).lower() 
    if not ("abstract" in mystr): 
    mylist.append(mystr) 

mylist = list(set(mylist)) 
return mylist 

回答

1

您可以使用SPARQL UNION

或者您可以使用SPARQL 1.1 VALUES將相同的查詢應用於多個資源。例如 -

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> 
    SELECT DISTINCT ?s ?pLabel ?oLabel ?o WHERE { 
    ?s ?p ?o. 
    VALUES ?s {<http://dbpedia.org/resource/Leipzig> <http://dbpedia.org/resource/Dresden>} 
    ?p rdfs:label ?pLabel . 
    ?o rdfs:label ?oLabel . 
    FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en")) 
    FILTER(LANG(?oLabel) = "" || LANGMATCHES(LANG(?oLabel), "en")) 
    } 
+0

我很確定UNION是我正在尋找的,但我試圖自己做這件事,但我似乎無法做到正確。如果我做了這些查詢的聯合,我似乎無法得到與原始2查詢相同的結果。我應該如何對這些查詢執行UNION? – Nick

+0

爲什麼不能使用VALUES?這樣更方便。它不起作用嗎? – AKSW

+0

你可以顯示你試過的UNION查詢嗎?什麼不適合它?請注意,在這種情況下,您必須保留主題的變量,否則您無法區分這兩種資源。 – AKSW