我自己搭建了博客,以后可能不太在CSDN上发博文了,https://www.qingdujun.com/ 。
在做“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):
解决方案:
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: .
@prefix rdf: .
@prefix rdfs: .
@prefix tdb: .
@prefix ja: .
@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 :
PREFIX rdf:
PREFIX rdfs:
SELECT * WHERE{
?x :movieTitle '功夫'.
?x ?p ?o.
}
''')
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["x"]["value"])
print(result["p"]["value"])
print(result["o"]["value"])
References:
[1] https://zhuanlan.zhihu.com/p/33224431
[2] https://jena.apache.org/documentation/fuseki2/fuseki-configuration.html
[3] http://jena.apache.org/documentation/fuseki2/fuseki-configuration.html#relationship-to-fuseki-1-configuration
[4] https://jena.apache.org/documentation/serving_data/