Wikidata - resultset.hasNext() returns false 尽管检索了结果

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

正如标题所描述的那样,我们 resultset.hasNext() returns false 出乎意料。

这是我的 SPARQL 查询和 Java 基于 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();
}

输出如下:

------------------------------------------------------
| 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      |
------------------------------------------------------

您只能在 Resultset 上迭代一次,这已经在便捷方法 ResultSetFormatter.out(...)

中发生了

我不知道你是否真的需要处理 ResultSet 两次,但如果是这样你可以创建一个 ResultSetRewindable 允许重置光标:

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();
}