天天看点

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不兼容。