Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jena: how to query data from model?

Is it possible to query data from a Model without writing sqarql-queries? Adding properties to resources or resources to models can be done easily, but I haven't found out yet, if there is a more efficient way to query data from a Model than using code the one below:

    String sparql = "SELECT ?thing ?str WHERE { " +
                        "?thing a <" + THING + "> . " +
                        "?thing <" + HAS_STRING + "> ?str . " +
                        "FILTER (?str = \"" + s + "\") . }";

    Query qry = QueryFactory.create(sparql);
    QueryExecution qe = QueryExecutionFactory.create(qry, getModel());
    ResultSet rs = qe.execSelect();

    while(rs.hasNext())
    {
        QuerySolution sol = rs.nextSolution();
        RDFNode str = sol.get("str"); 
        RDFNode thing = sol.get("thing"); 

        ...
    }

    qe.close(); 
like image 940
Pedro Avatar asked Mar 27 '12 21:03

Pedro


1 Answers

You can use the list* methods available on a Jena Model: http://incubator.apache.org/jena/documentation/javadoc/jena/com/hp/hpl/jena/rdf/model/Model.html

For example, model.listStatements() or model.listStatements ((Resource)null, RDF.type, (RDFNode)null), etc.

You can find an example of model.listStatements() here: https://github.com/castagna/jena-examples/blob/995d7acf8fcb3f9a8f7264dfd0902cdddfc00279/src/main/java/org/apache/jena/examples/ExampleAPI_01.java

See also the section "Querying a Model" in the Jena tutorial on the Jena website: http://incubator.apache.org/jena/tutorials/rdf_api.html#ch-Querying%20a%20Model

One last comment, in terms of efficiency you should not see much difference, indeed I do not think there is a difference. For every list* methods in Model you can write a very simple SPARQL query and compare performances yourself. If what you want is available as a method of a Model then use it, but you'll soon find that when you want to do more, SPARQL queries can be more concise and allows you to get back just exactly what you need with less code.

like image 143
castagna Avatar answered Sep 29 '22 15:09

castagna