我想从DBPedia获取与Jupiter相关的所有资源/对象对,并通过Apache Jena构造在java中以RDF格式输出结果的查询。我的构造查询在http://dbpedia.org/sparql服务中工作,如下所示:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
construct {<http://dbpedia.org/resource/Jupiter> ?o ?r. }
{{ <http://dbpedia.org/resource/Jupiter> ?o ?r }
UNION
{?o ?r <http://dbpedia.org/resource/Jupiter>}}
我编写了一个java程序,用RDF格式在Jupiter.rdf文件中编写CONSTRUCT查询结果,但它显示异常。我的java代码如下:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSetFactory;
import org.apache.jena.query.ResultSetRewindable;
public class Jupiter {
public static void main(String[] args) throws IOException {
ParameterizedSparqlString querystring = new ParameterizedSparqlString(""
+ "construct {<http://dbpedia.org/resource/Jupiter> ?o ?r } where {{ <http://dbpedia.org/resource/Jupiter> ?o ?r } UNION"
+ " {?r ?o <http://dbpedia.org/resource/Jupiter>}}");
QueryExecution exec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", querystring.asQuery());
ResultSetRewindable result = ResultSetFactory.makeRewindable(exec.execSelect());
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Jupiter.rdf")))
{
while (result.hasNext()) {
QuerySolution querysolution = result.next();
bw.write(querysolution.get("o").toString());
bw.write(querysolution.get("r").toString());
}
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
因此例外:
Exception in thread "main" org.apache.jena.sparql.resultset.ResultSetException: Not a string: key: value
at org.apache.jena.sparql.resultset.JSONInput.stringOrNull(JSONInput.java:230)
at org.apache.jena.sparql.resultset.JSONInput.parseOneTerm(JSONInput.java:201)
at org.apache.jena.sparql.resultset.JSONInput.parse(JSONInput.java:172)
at org.apache.jena.sparql.resultset.JSONInput.process(JSONInput.java:100)
at org.apache.jena.sparql.resultset.JSONInput.fromJSON(JSONInput.java:63)
at org.apache.jena.query.ResultSetFactory.fromJSON(ResultSetFactory.java:331)
at org.apache.jena.sparql.engine.http.QueryEngineHTTP.execResultSetInner(QueryEngineHTTP.java:385)
at org.apache.jena.sparql.engine.http.QueryEngineHTTP.execSelect(QueryEngineHTTP.java:351)
你能告诉我为什么会这样吗?非常感谢您的帮助
答案 0 :(得分:1)
您有SPARQL CONSTRUCT查询,而不是SELECT查询。因此,您必须致电exec.execConstruct()
,然后您将获得一个Model
对象,其中包含三元组而不是ResultSet
。