如何在Jena中将SPARQL查询转换为RDF文件?

时间:2013-03-12 20:25:27

标签: java rdf sparql jena

我正在尝试直接从Oracle数据库的SPARQL查询输出RDF / XML文件。 由于我在ResultSet对象中验证了结果,因此查询工作正常。

但是,我不确定如何从那里开始。我想我想为每个QuerySolution创建一个Statement,然后将它添加到Model中。但是我无法想出办法,因为我无法找到获取谓词值的方法。

任何帮助都会受到赞赏,并暗示我是否走正路。

QueryExecution qe = QueryExecutionFactory.create(query, oracleSemModel) ;       
ResultSet results = qe.execSelect();

Model model = ModelFactory.createDefaultModel();

while (results.hasNext())
{
    QuerySolution result = results.next();
    Resource  subject   =  result.getResource("s");   // get the subject
    Property  predicate =  result.getProperty("p");   // <-- THIS FUNCTION DOESN'T EXIST
    RDFNode   object    =  result.get("o");           // get the object

    Statement stmt = ResourceFactory.createStatement(subject, predicate, object);

    model.add(stmt);
}

model.write(System.out, "RDF/XML-ABBREV");

1 个答案:

答案 0 :(得分:6)

您尚未显示查询,但可能是以下形式:

SELECT ?s ?p ?o
WHERE {
    ...
}

如果将SELECT替换为CONSTRUCT,您希望实现的目标是直截了当的:

CONSTRUCT { ?s ?p ?o }
WHERE {
    ...
}

CONSTRUCT通过获取三重模板并将每个解决方案绑定到模板,然后将其添加到结果模型,从而构建(构造)模型。在你的情况下,这个模板只是{ ?s ?p ?o },即使用?s作为主题等。但是可以使用更精细的模式,只需在查询结果中的值的位置写入您期望的RDF变量

最终代码:

QueryExecution qe = QueryExecutionFactory.create(query, oracleSemModel) ;
Model model = qe.execConstruct();
// there is no step 3