如何使用Trinity RDF正确连接Apache Jena Fuseki三元组存储
我目前正在开展一个项目,需要向部署在Apache Jena Fuseki三元组存储上的图插入并查询数据,但无法成功连接该存储。我已尝试两种方法:
方法1
store = new FusekiStore("triplestore.project.customer.de", "Datasetname", "User", "fusekiPassword"); _model = store.GetModel(new Uri("https://triplestore.project.customer.de/Datasetname/"));
使用此方法时,store已创建,调试显示store.IsReady = true,_model也已创建,但检查时发现_model.IsEmpty抛出System.UriFormatException,调用_model.CreateResource<T>(new Uri("https://triplestore.project.customer.de/Datasetname/" + id))时也会出现相同异常。
方法2
var cred = new NetworkCredential("User", fusekiPassword); store = StoreFactory.CreateSparqlEndpointStore(new Uri("https://triplestore.project.customer.de/Datasetname/data"), null, cred); _model = store.GetModel(new Uri("https://triplestore.project.customer.de/Datasetname/"));
store同样已创建,但store.IsReady抛出System.NotImplementedException。忽略该异常尝试创建资源_model.CreateResource<T>(new Uri("https://triplestore.project.customer.de/Datasetname/" + id))时,出现以下错误:
VDS.RDF.Query.RdfQueryException: "A HTTP Error occurred while trying to make the SPARQL Query, see inner exception for details InnerException {"The remote server returned an error: (400) Bad Request."} System.Exception {System.Net.WebException}
正确连接步骤
使用FusekiStore的正确参数
Trinity RDF的FusekiStore构造函数第一个参数是Fuseki主机名,需注意不带https://这类协议前缀;若Fuseki使用非默认端口,要追加端口号。获取模型时,模型URI需对应Fuseki数据集的图URI,默认图直接用数据集基础URI即可,同时要保证URI格式合法。修正后的方法1代码:
// 主机名不带协议前缀,有非默认端口需追加,例如 triplestore.project.customer.de:3030 store = new FusekiStore("triplestore.project.customer.de", "Datasetname", "User", "fusekiPassword"); // 默认图直接用数据集URI,指定图则用对应图URI Uri modelUri = new Uri("https://triplestore.project.customer.de/Datasetname/"); _model = store.GetModel(modelUri);针对
UriFormatException:拼接id时要对特殊字符进行URI编码,确保最终URI格式标准,示例代码:string encodedId = Uri.EscapeDataString(id); var resourceUri = new Uri($"https://triplestore.project.customer.de/Datasetname/{encodedId}"); _model.CreateResource<T>(resourceUri);使用SPARQL Endpoint方式的注意点
StoreFactory.CreateSparqlEndpointStore需要传入SPARQL查询和更新端点的URI,而非数据端点。Fuseki的标准端点为:- 查询端点:
https://triplestore.project.customer.de/Datasetname/query - 更新端点:
https://triplestore.project.customer.de/Datasetname/update
修正后的方法2代码:
var cred = new NetworkCredential("User", fusekiPassword); // 分别传入查询和更新端点 var queryEndpoint = new Uri("https://triplestore.project.customer.de/Datasetname/query"); var updateEndpoint = new Uri("https://triplestore.project.customer.de/Datasetname/update"); store = StoreFactory.CreateSparqlEndpointStore(queryEndpoint, updateEndpoint, cred); // 获取模型时,URI对应Fuseki中的图URI,默认图用数据集URI即可 _model = store.GetModel(new Uri("https://triplestore.project.customer.de/Datasetname/"));400 Bad Request通常是因为端点URI错误,
/data是文件上传端点,并非SPARQL操作端点,需替换为正确的查询/更新端点。- 查询端点:
额外检查项
- 确认Fuseki权限:确保用户
User拥有目标数据集的读写权限,避免因权限不足导致请求失败。 - 检查网络连接:确认应用可访问Fuseki服务器端口,无防火墙或代理阻挡请求。
- 验证URI格式:所有涉及的URI需合法,避免出现空格、未转义的特殊字符。
内容的提问来源于stack exchange,提问作者TheBlackOne

