Jena: how to query data from model?
Asked Answered
D

1

7

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(); 
Distend answered 27/3, 2012 at 21:57 Comment(0)
L
6

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.

Leipzig answered 29/3, 2012 at 7:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.