简体   繁体   中英

How to convert a SPARQL query into an RDF file in Jena?

I am trying to output an RDF/XML file directly from an SPARQL query from an Oracle database. The query is working fine as I've verified the results in the ResultSet object.

However, I'm not sure how to proceed from there. I think I want to create a Statement for each QuerySolution and then add it to the Model. However I can't figure out a way to do it, because I can't find a way to get the predicate value.

Any help would be appreciated, as well as hints whether I am going down the right path.

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");

You haven't shown the query, but it's presumably of the form:

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

What you want to achieve is straightforward if you replace SELECT with CONSTRUCT :

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

CONSTRUCT makes (constructs) a model as a result by taking a triple template and binding each solution to it, then adding that to a result model. In you case this template is simply { ?s ?p ?o } , ie use ?s as the subject, etc. However it is possible to use more elaborate patterns, just write the RDF you expect with variables in the positions for values from the query results.

The final code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM