Wikidata - resultset.hasNext() returns false despite the results are retrieved

804 Views Asked by At

As the title clearly describes, we resultset.hasNext() returns false unexpectedly.

Here is my SPARQL query and Java source code based on Jena:

SELECT ?s ?label WHERE { ?s rdfs:label ?label. FILTER(CONTAINS(LCASE(?label), "university"@en)). } LIMIT 5

Query query = QueryFactory.create(PREFIX + sparqlQuery);
QueryExecution queryExecution = QueryExecutionFactory.sparqlService("https://query.wikidata.org/sparql", PREFIX + sparqlQuery);
try {
    ResultSet results = queryExecution.execSelect();
    ResultSetFormatter.out(System.out, results, query);
    while (results.hasNext()) { // returns false
        QuerySolution querySolution = results.next();
        System.out.println(querySolution.getResource("s"));
    }
} catch (Exception ex) {
    System.err.println(ex.getMessage());
} finally {
    queryExecution.close();
}

Here is the output:

------------------------------------------------------
| s        | label                                   |
======================================================
| wd:Q1060 | "Technical University of Hamburg"@en    |
| wd:Q1060 | "Technical University of Hamburg"@en-ca |
| wd:Q1060 | "Technical University of Hamburg"@en-gb |
| wd:Q1060 | "Technical University of Hamburg"@nl    |
| wd:Q4027 | "Jean Moulin University Lyon 3"@en      |
------------------------------------------------------
1

There are 1 best solutions below

1
On BEST ANSWER

You can only iterate once over the Resultset, and this already happens in the convenience method ResultSetFormatter.out(...)

I don't know whether you really need to process the ResultSet twice, but if so you can create a ResultSetRewindable which allows to reset the cursor:

Query query = QueryFactory.create(PREFIX + sparqlQuery);
QueryExecution queryExecution = QueryExecutionFactory.sparqlService("https://query.wikidata.org/sparql", PREFIX + sparqlQuery);
try {
    ResultSet rs = queryExecution.execSelect();
    ResultSetRewindable results = ResultSetFactory.copyResults(rs);
    ResultSetFormatter.out(System.out, results, query);
    results.reset();
    while (results.hasNext()) { // returns false
        QuerySolution querySolution = results.next();
        System.out.println(querySolution.getResource("s"));
    }
} catch (Exception ex) {
    System.err.println(ex.getMessage());
} finally {
    queryExecution.close();
}