在做“Apache jena SPARQL endpoint及推理”时,遇到了不少问题,主要原因是jena-fuseki版本更新了。以下对问题解决方案做下笔记。想了解更多,请查阅底部参考文献。
Question 1: JENA_HOME not set
解决方案:
(对于Win7)我的电脑->属性->高级系统设置->环境变量,在系统变量
里添加一项JENA_HOME:
JENA_HOME
D:\AppsPath\apache-jena-3.8.0
当然,也可以顺带将FUSEKI_HOME添加上,
FUSEKI_HOME
D:\AppsPath\apache-jena-fuseki-3.8.0
最后,在Path
中添加这些内容:%FUSEKI_HOME%\;%JENA_HOME%\bin;
Question 2: Server ERROR Exception in initialization: caught: [line: 1, col: 7 ] Bad character in IRI (space): <?xml[space]...>
解决方案:
Protege工具默认生成的本体格式为RDF/XML Syntax格式,这里更改为Turtle Syntax
。
Question 3: Server ERROR Exception in initialization: the loading of content into file:///D:/AppsPath/apache-jena-fuseki-3.8.0/run/configuration/fuseki_conf.ttl#model_inf was aborted because of Read-only object file
解决方案:
这是由于fuseki版本升级所导致的问题,ja:baseModel <#tdbGraph> ;改为 ja:MemoryModel <#tdbGraph> ;
即可顺利运行。
Question 4: 访问http://localhost:3030
执行SPARQL查询时,页面获取到的数据为空?
解决方案:
这时需要重写D:\AppsPath\apache-jena-fuseki-3.8.0\run\configuration\fuseki_conf.ttl
配置文件,以下为我重写的fuseki_conf.ttl文件内容(请修改对应的tdb路径
):
@prefix fuseki: <http://jena.apache.org/fuseki#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix tdb: <http://jena.hpl.hp.com/2008/tdb#> .
@prefix ja: <http://jena.hpl.hp.com/2005/11/Assembler#> .
@prefix : <#> .
<#service3> rdf:type fuseki:Service ;
fuseki:name "kg_demo_movie" ; # http://host:port/tdb
fuseki:serviceQuery "sparql" ; # SPARQL query service
fuseki:dataset <#dataset> ;
.
<#dataset> rdf:type tdb:DatasetTDB ;
tdb:location "E:/data/tdb" ;
# Query timeout on this dataset (1s, 1000 milliseconds)
ja:context [ ja:cxtName "arq:queryTimeout" ; ja:cxtValue "1000" ] ;
# Make the default graph be the union of all named graphs.
## tdb:unionDefaultGraph true ;
自定义推导规则,见《jena fuseki 自定义推导规则(OWLFBRuleReasoner推导机)》。
附录:Python查询代码
这里请求连接可以为http://localhost:3030/xxx/sparql
,或者http://localhost:3030/xxx/query
,两个都可以查询到数据。
# -*- coding: utf-8 -*-
from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper("http://localhost:3030/kg_demo_movie/sparql")
sparql.setQuery(r'''
PREFIX : <http://www.kgdemo.com#>
PREFIX rdf: <http://www.trgj888.com /1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.fengshen157.com/ www.w3.org/2000/01/rdf-schema#>
SELECT * WHERE{
?x :movieTitle '功夫'.
?x ?p ?o.
}
''')
sparql.setReturnFormat(JSON)
results = sparql.query(www.thd540.com).convert(www.taohuayuan178.com)
for result in results["results"]www.mhylpt.com/ ["bindings"]:
print(result["x"]["value"])
print(result["p"]www.yongshiyule178.com["value"])
print(result["o"]["value"])