我尝试使用 REST API 在我的 neo4j 数据库上运行 SPARQL 查询。为了获得 SPARQL 端点,我安装了 Noe4j SPARQL 插件(https://github.com/neo4j-contrib/sparql-plugin)。我的系统现在公开了这些 sparql 端点:
http://localhost:7474/db/data/ext/SPARQLPlugin/graphdb/insert_quad
http://localhost:7474/db/data/ext/SPARQLPlugin/graphdb/execute_sparql
我试图使用第二个来执行查询。HTTP POST 请求应该类似于http://neo4j-contrib.github.io/sparql-plugin/中的“示例 2”,但查询稍微容易一些。这是源代码:
private static final String ENDPOINT = "http://localhost:7474/db/data/ext/SPARQLPlugin/graphdb/execute_sparql";
private static String query = "SELECT ?x WHERE {?x ?y ?z} LIMIT 5";
public static void main(String[] args) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ENDPOINT);
// Request parameters and other properties.
httppost.addHeader(new BasicHeader("Method", "POST"));
httppost.addHeader(new BasicHeader("Accept", "application/json"));
httppost.addHeader(new BasicHeader("Content-Type", "application/json"));
JSONObject holder = new JSONObject();
holder.put("query", query);
System.out.println(holder.toString());
httppost.setEntity(new StringEntity(holder.toString()));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
System.out.println("HEADER:");
System.out.println("Status code : " + response.getStatusLine().getStatusCode());
Header[] hlist = response.getAllHeaders();
for (int i = 0; i < hlist.length; i++) {
System.out.print(hlist[i].getName() + " ");
System.out.println(hlist[i].getValue());
}
System.out.println("-----");
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader rd = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println("x " + line);
}
} else {
System.out.println("Entity is null");
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
不幸的是,我没有得到想要的输出。输出是:
{"query":"SELECT ?x WHERE {?x ?y ?z} LIMIT 5"}
HEADER:
Status code : 200
Content-Length 4
Content-Type application/json; charset=UTF-8
Access-Control-Allow-Origin *
Server Jetty(6.1.25)
-----
x null
我很确定这个 SPARQL 查询是正确的;在安装 sparqpl-plugin 时我也没有注意到任何问题,所以我不知道为什么我会得到“null”。我试过通过谷歌寻找解决方案,但我没有发现任何有用的东西。我怎样才能解决这个问题 ?我使用在 Windows 7 上运行的 Neo4j 1.9.2 社区版
安装的 sparql 插件的版本是“0.2 SNAPSHOT”
编辑 1:如果我运行这个查询:
SELECT ?x WHERE {?x ?y ?z} LIMIT 0
输出是:
{"query":"SELECT ?x WHERE {?x ?y ?z} LIMIT 0"}
HEADER:
Status code : 200: OK
Content-Length 3
Content-Type application/json; charset=UTF-8
Access-Control-Allow-Origin *
Server Jetty(6.1.25)
-----
x [ ]
也许这有助于发现错误。
我还尝试从 Neo4j 的 HTTP 控制台运行查询:
http> POST http://localhost:7474/db/data/ext/SPARQLPlugin/graphdb/execute_sparql {"query":"select ?x where { graph ?g { ?x ?y ?z } }"}
==> 200 OK
==> null
http> POST http://localhost:7474/db/data/ext/SPARQLPlugin/graphdb/execute_sparql {"query":"select ?x where { ?x ?y ?z }"}
==> 200 OK
==> null
编辑 2:
我尝试重新下载并构建插件。之后我通过在 NEO4J_HOME/plugins/sparql 解压缩它来安装它。然后,在我启动 Neo4j.bat 之后,我执行了我的 java 代码。控制台出现以下错误:
x {
x "message" : "com/tinkerpop/blueprints/impls/neo4j/Neo4jGraph",
x "exception" : "NoClassDefFoundError",
x "fullname" : "java.lang.NoClassDefFoundError",
x "stacktrace" : [ "org.neo4j.server.plugin.sparql.SPARQLPlugin.initSail(SPARQLPlugin.java:90)", "org.neo4j.server.plugin.sparql.SPARQLPlugin.executeSPARQL(SPARQLPlugin.java:61)", "java.lang.reflect.Method.invoke(Unknown Source)", "org.neo4j.server.plugins.PluginMethod.invoke(PluginMethod.java:57)", "org.neo4j.server.plugins.PluginManager.invoke(PluginManager.java:168)", "org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension(ExtensionService.java:300)", "org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension(ExtensionService.java:122)", "java.lang.reflect.Method.invoke(Unknown Source)", "org.neo4j.server.rest.security.SecurityFilter.doFilter(SecurityFilter.java:112)" ],
x "cause" : {
x "message" : "com.tinkerpop.blueprints.impls.neo4j.Neo4jGraph",
x "exception" : "ClassNotFoundException",
x "stacktrace" : [ "java.net.URLClassLoader$1.run(Unknown Source)", "java.net.URLClassLoader$1.run(Unknown Source)", "java.security.AccessController.doPrivileged(Native Method)", "java.net.URLClassLoader.findClass(Unknown Source)", "java.lang.ClassLoader.loadClass(Unknown Source)", "sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)", "java.lang.ClassLoader.loadClass(Unknown Source)", "org.neo4j.server.plugin.sparql.SPARQLPlugin.initSail(SPARQLPlugin.java:90)", "org.neo4j.server.plugin.sparql.SPARQLPlugin.executeSPARQL(SPARQLPlugin.java:61)", "java.lang.reflect.Method.invoke(Unknown Source)", "org.neo4j.server.plugins.PluginMethod.invoke(PluginMethod.java:57)", "org.neo4j.server.plugins.PluginManager.invoke(PluginManager.java:168)", "org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension(ExtensionService.java:300)", "org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension(ExtensionService.java:122)", "java.lang.reflect.Method.invoke(Unknown Source)", "org.neo4j.server.rest.security.SecurityFilter.doFilter(SecurityFilter.java:112)" ],
x "fullname" : "java.lang.ClassNotFoundException"
x }
x }
我发现,“com.tinkerpop.blueprints.impls.neo4j.Neo4jGraph”是一些“blueprints-neo4j-graph.jar”的一部分。我的 sparql/ 文件夹中缺少此 jar 文件,因此我搜索了最新的 jar 文件并添加了“blueprints-neo4j-graph-2.5.0-20130916.151744-5.jar”。重新启动服务器后,错误不再出现,但我仍然得到“null”作为结果(在两个查询中的任何一个)
编辑 3:我还尝试从 github 页面复制“BerlinDatasetTest.java”的某些部分neof4 sparql-plugin 并手动运行它(添加所有必要的 jar 文件后的 ofc)。这是源代码:
public String runQuery(String raw_query) {
String q_result = "";
Sail sail = new GraphSail( new Neo4jGraph("my_db/") );
try {
sail.initialize();
QueryParser parser = new SPARQLParserFactory().getParser();
ParsedQuery query = null;
CloseableIteration<? extends BindingSet, QueryEvaluationException> sparqlResults;
SailConnection conn = sail.getConnection();
query = parser.parseQuery(raw_query, "http://localhost:7474");
sparqlResults = conn.evaluate( query.getTupleExpr(),
query.getDataset(), new EmptyBindingSet(), false );
while ( sparqlResults.hasNext() ) {
q_result += "; " + sparqlResults.next();
}
conn.close();
sail.shutDown();
} catch (Exception e) {
e.printStackTrace();
}
return q_result;
}
这是我得到的结果
java.lang.NullPointerException
at com.tinkerpop.blueprints.oupls.sail.GraphSailConnection.toSesame(GraphSailConnection.java:729)
at com.tinkerpop.blueprints.oupls.sail.GraphSailConnection.fillStatement(GraphSailConnection.java:636)
at com.tinkerpop.blueprints.oupls.sail.GraphSailConnection.access$800(GraphSailConnection.java:36)
at com.tinkerpop.blueprints.oupls.sail.GraphSailConnection$StableStatementIteration.next(GraphSailConnection.java:624)
at com.tinkerpop.blueprints.oupls.sail.GraphSailConnection$StableStatementIteration.next(GraphSailConnection.java:589)
at info.aduna.iteration.IterationWrapper.next(IterationWrapper.java:71)
at net.fortytwo.sesametools.QueryEvaluationIteration.next(QueryEvaluationIteration.java:45)
at net.fortytwo.sesametools.QueryEvaluationIteration.next(QueryEvaluationIteration.java:16)
at info.aduna.iteration.IterationWrapper.next(IterationWrapper.java:71)
at info.aduna.iteration.FilterIteration.findNextElement(FilterIteration.java:69)
at info.aduna.iteration.FilterIteration.hasNext(FilterIteration.java:43)
at info.aduna.iteration.ConvertingIteration.hasNext(ConvertingIteration.java:62)
at info.aduna.iteration.ConvertingIteration.hasNext(ConvertingIteration.java:62)
at info.aduna.iteration.IterationWrapper.hasNext(IterationWrapper.java:57)
at org.openrdf.sail.helpers.SailBaseIteration.hasNext(SailBaseIteration.java:50)
at src.QueryTest.runQuery(QueryTest.java:113)
at src.QueryTest.main(QueryTest.java:140)
“QueryTest.java”是我在其中运行此函数的 java 类的名称。
编辑 4:看来,结果只是空的,如果
query.getDataset()
变为空(这在两个查询中都发生)如果我添加 FROM 子句或开始在 WHERE 部分中使用 URL,则 query.Dataset() 不再为空,并且我得到一个空结果(这不是空)。这些是两个“工作”查询:
select ?x from <localhost:7474> where { graph ?g { ?x ?y ?z } }
select ?x where { graph ?g { ?x <http://localhost:7474#knows> ?z } }
我仍然没有得到任何结果。