天天看點

SPARQL查詢內建python腳本及jena簡介

from SPARQLWrapper import SPARQLWrapper ,JSON

sparql = SPARQLWrapper("http://localhost:2020/sparql")
sparql.setQuery("""
    PREFIX : <http://www.kgdemo.com>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX vocab: <http://localhost:2020/resource/vocab/>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX map: <http://localhost:2020/resource/#>
    PREFIX db: <http://localhost:2020/resource/>
    
    SELECT ?n WHERE {
        ?s rdf:type :Movie.
        ?s :movieTitle '英雄'.
        ?a :hasActedIn ?s.
        ?a :personName ?n
    }
""")
sparql.setReturnFormat(JSON)
#這裡的convert是為了将<class 'SPARQLWrapper.Wrapper.QueryResult'>轉換為字典
results = sparql.query().convert()
#print(type(results))
#results的格式為:
#{'head': {'vars': ['n']}, 'results': {'bindings': [{'n': {'type': 'literal', 'value': '李連傑'}},
# {'n': {'type': 'literal', 'value': '梁朝偉'}}, {'n': {'type': 'literal', 'value': '張曼玉'}},
# {'n': {'type': 'literal', 'value': '章子怡'}}, {'n': {'type': 'literal', 'value': '甄子丹'}}]}}
for result in results['results']['bindings']:
    print(result['n']['value'])      

初始化Wrapper需要的參數是endpoint對外提供服務的連結,D2RQ預設的連結是“​​http://localhost:2020/sparql”。​​

需要注意的是D2RQ是以虛拟RDF圖的方式來通路關系資料庫,在通路頻率不高,資料變動頻繁的場景下,這種方式比較合适。對于通路頻率比較高的場景(比如KBQA),将資料轉為RDF再提供服務更為合适。

SPARQL的缺點是:

1. 不支援直接将RDF資料通過endpoint釋出到網絡上。

2. 不支援推理。

而Apache Jena可以解決上面的兩個問題。

Apache Jena(後文簡稱Jena),是一個開源的Java語義網架構(open source Semantic Web Framework for Java),用于建構語義網和連結資料應用。下面是Jena的架構圖:

SPARQL查詢內建python腳本及jena簡介

1. TDB是Jena用于存儲RDF的元件,是屬于存儲層面的技術。在單機情況下,它能夠提供非常高的RDF存儲性能。目前TDB的最新版本是TDB2,且與TDB1不相容。