在使用Jena数据集中的sparql FROM子句跨多个图形可靠地发出sparql查询时,我们遇到了麻烦。
以下是问题的一个示例:
final String subject = "http://example.com/ont/breakfast#espresso";
final String graph1 = "http://example.com/ont/breakfast/graph#espresso_definition";
final String graph2 = "http://example.com/ont/breakfast/graph#espresso_decoration";
// Add some triples to graphs within the dataset
Dataset dataset = DatasetFactory.create();
Model modelG1 = dataset.getNamedModel(graph1);
Resource espressoTypeG1 = modelG1.createResource(subject)
.addProperty(RDF.type, OWL.Class);
Resource espressoLabelG1 = modelG1.createResource(subject)
.addProperty(RDFS.label, "Espresso");
Model modelG2 = dataset.getNamedModel(graph2);
Resource espressoLabelG2 = modelG2.createResource(subject)
.addProperty(RDFS.label, "Black Gold");
// The query to execute - returns no results
String queryString = "select * FROM <" + graph1 + "> FROM <" + graph2 + "> " +
"{ <" + subject + "> ?p ?o }";
// This, however, works:
// String queryString = "select * { graph ?g { <" + subject + "> ?p ?o } }";
// Run the query
Query query = QueryFactory.create(queryString);
try (QueryExecution qe = QueryExecutionFactory.create(query, dataset)) {
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution result = results.next();
System.out.println(result);
}
}
值子句和 graph 关键字的组合已帮助我们解决了大多数需要在同一查询中处理多个图形的情况。在某些查询中,这变得非常笨拙或完全无效。
我们如何做才能在单个数据集中的多个模型联合中正确发出查询?
请注意,查询在编译时未知,因此我们不能依靠手动在Java代码中创建 model 的并集。此外,通常使用从文件加载,sparql更新和对 dataset.asDatasetGraph()。add(...)的调用的组合来添加数据。
答案 0 :(得分:4)
FROM
和FROM NAMED
的处理方式取决于所使用的Dataset
实现是否支持它,默认的内存中实现默认不支持它。
要强制使用数据集,您可以使用DynamicDatasets
和DatasetDescription
帮助器类来解析查询指定的数据集,例如
Dataset resolvedDataset =
DynamicDatasets.dynamicDataset(DatasetDescription.create(query), dataset, false);
try (QueryExecution qe = QueryExecutionFactory.create(query, resolvedDataset)) {
// Normal result processing logic goes here...
}