无法从此SPARQL查询中获得任何结果

时间:2014-09-26 18:17:07

标签: java sparql jena dbpedia

我之前问了一个问题

Generate an incremental SPARQL query

感谢上帝,我设法解决它。

这是我的解决方案:

private String completeQuery(String coreQuery){
    String completeQuery = "";
    completeQuery += "SELECT * WHERE {"+ "\n";
    completeQuery += coreQuery + "\n";
    completeQuery =completeQuery + "}" + "\n" +"limit 5" ;
    return completeQuery;
}

public String link(String object1, String object2, int distance){
    if(distance == 1){
        String Quer = "<http://dbpedia.org/resource/"+object1+">" + " ?pre1 " +"<http://dbpedia.org/resource/"+object2+">";
        return completeQuery(Quer);
    } 
    else {
        String query = "<http://dbpedia.org/resource/"+object1+">" + " ?pre1 ?obj1 " + ".\n";
        for(int i = 1; i < distance-1; i++){
            query += "?obj" + i + " ?pre" + (i+1) + " ?obj" + (i+1) + ".\n" ;

        }
        query  += "?obj" + (distance-1) + " ?pre" + distance + " " + "<http://dbpedia.org/resource/"+object2+">";
        return completeQuery(query);
    }
}

从主要的我只是尝试打印查询字符串以确定它是否正确:

String queryString = "";

    int maxDistance =2;
    PathFinder pf = new PathFinder();

    for (int distance = 1; distance<=maxDistance ; distance ++)
    {
        System.out.println("\nQueries for distance: "+distance);
        queryString = pf.link("Lionel_Messi","Spanish_language",distance);
        System.out.println(queryString);}

到目前为止结果还不错

Queries for distance1: SELECT * WHERE {<http://dbpedia.org/resource/Lionel_Messi> ?pre1 <http://dbpedia.org/resource/Spanish_language>}limit 5

Queries for distance2: SELECT * WHERE { <http://dbpedia.org/resource/Lionel_Messi> ?pre1 ?obj1 . ?obj1 ?pre2 <http://dbpedia.org/resource/Spanish_language> }limit 5

现在,我正在尝试执行这些查询,但我不知道该怎么做 如果它是一个简单的查询,例如(select?abstract where ...),执行将是例如:

QueryExecution qe = QueryExecutionFactory.sparqlService(service, query);

                ResultSet results = qe.execSelect();
                for (; results.hasNext();){
                    QuerySolution sol = (QuerySolution) results.next();
                    System.out.println(sol.get("?abstract"));
                }

但如果查询类似(select * where),如何在不知道我想要打印的特定元素的情况下获得结果?这完全取决于我的距离以及它将返回的查询....

1 个答案:

答案 0 :(得分:3)

这不仅仅是通过SPARQL解决的问题 - 您需要使用您用来处理查询和结果的API工具包的功能。由于您使用的是Jena,因此您应该查看Jena的ResultSet对象的文档。它有一个方法getResultVars(),它为您提供了一个包含结果中所有变量名称的列表。然后,您可以使用它来迭代结果并在每个解决方案中获取变量绑定,例如简单地打印它们:

 List<String> varNames = results.getResultVars();

 while(results.hasNext()) {
       QuerySolution sol = (QuerySolution) results.next();
       for (String var: varNames) {
              System.out.println("value of " + var + ": " + sol.get(var));
       }
 }