Search code examples
javasparqlrdfjenafuseki

Java SPARQL Select query


I wrote a SELECT statement that returns me all data from the fuseki-server. My question is how I can get a list with all names available below the o column (see the attached image)?

enter image description here

For example, I need an array that will contain the following items: [Pavel Ionut, Cirstea Aurel, Test1]

This is my SELECT statement, which should be changed to return only the name property ... but I did not use SPARQL before and any solution would help me a lot.

QueryExecution qe = QueryExecutionFactory.sparqlService(
        "http://localhost:3030/Date/query", "SELECT * WHERE {?s ?p ?o}");
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out, results);
qe.close();
System.out.println(results);

Solution

  • To return the set of objects from all existing s-p-o triples use this SPARQL query:

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

    To only get the names, try:

    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    SELECT DISTINCT ?n WHERE { ?s dc:name ?n . }
    

    or just:

    SELECT DISTINCT ?n WHERE { ?s <http://purl.org/dc/elements/1.1/name> ?n . }
    

    The specification contains some good examples:

    To iterate over the result set of the query above with Apache Jena Fuseki in Java, this might work:

    while (results.hasNext()) {
        QuerySolution querySolution = results.next();
        RDFNode node = querySolution.get("n");
        String name = node.asLiteral().getString();
        System.out.println(name);
    }