Neo4j SPARQL插件REST用法 [英] Neo4j SPARQL-plugin REST usage

查看:137
本文介绍了Neo4j SPARQL插件REST用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用REST API在我的neo4j数据库上运行SPARQL查询.为了获得SPARQL端点,Ive安装了Noe4j SPARQL-plugin( https://github.com/neo4j-contrib/sparql-plugin ).我的系统现在公开了这些sparql端点:

Im trying to run a SPARQL-query on my neo4j database by using the REST API. For getting a SPARQL-endpoint, Ive installed the Noe4j SPARQL-plugin (https://github.com/neo4j-contrib/sparql-plugin). My system now exposes these sparql-endpoints:

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中的示例2". github.io/sparql-plugin/,查询稍微简单一些. 这是源代码:

Im trying to use the sencond one to execute queries. The HTTP POST Request is supposed to be like "Example 2" in http://neo4j-contrib.github.io/sparql-plugin/ with a slightly easier query. This is the source-code:

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

不幸的是,我没有得到想要的输出.输出为:

Unfortunately, I dont get the desired output. The output is:

{"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".


如果我运行此查询:

I´m pretty sure that this SPARQL query is correct; I also didnt notice any problems upon installing the sparqpl-plugin, so I have no idea why I get "null" as result. Ive tried looking for a solution via google, but I didnt find anything helpful. How can I fix this ? Im using the Community-Edition of Neo4j 1.9.2 running on Windows 7 The version of the installed sparql plugin is "0.2 SNAPSHOT"


EDIT 1: If I run this query:

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

也许这有助于发现错误.

Maybe this helps at finding the error.

我还尝试过从Neo4j的HTTP控制台运行查询:

I´ve also tried running queries from the HTTP Console of Neo4j:

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



我试图重新下载并构建插件.之后,我通过将其解压缩到NEO4J_HOME/plugins/sparql进行安装.然后,在启动Neo4j.bat之后,我执行了Java代码.控制台出现以下错误:



EDIT 2: I´ve tried to re-download and build the plugin. Afterwards I installed it, by unzipping it at NEO4J_HOME/plugins/sparql. Then, after I started Neo4j.bat, I executed my java-code. The following error came up at the console:

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"(在两个查询中的任何一个处)

我也尝试从neof4 sparql-plugin的github页面上摘录"BerlinDatasetTest.java"的某些部分,并手动运行它(添加所有必要的jar文件后,ofc).这是源代码:

I´ve found, that "com.tinkerpop.blueprints.impls.neo4j.Neo4jGraph" is part of some "blueprints-neo4j-graph.jar". This jar-file was missing in my sparql/ folder, so I searched for the most recent jar file and added "blueprints-neo4j-graph-2.5.0-20130916.151744-5.jar". After restarting the server, the error doesnt come up anymore, but I still get "null" as result (at either of both queries)

EDIT 3: Ive also tried coying some parts of the "BerlinDatasetTest.java" from the github page of the neof4 sparql-plugin and running it manually (ofc after adding all necessary jar files). This is the source code:

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类的名称.

"QueryTest.java" is the name of the java-class in which I run this function.

EDIT 4: It appears, that the result is only null, if

query.getDataset()

变为null(在两个查询中都发生)如果我添加FROM子句或开始在WHERE部分中使用URL,则query.Dataset()不再为null,并且Im得到空结果(不是null).这是两个有效"查询:

becomes null (which happens at both of the queries) If I add a FROM clause or start using URLs inside the WHERE-part, query.Dataset() isnt null anymore and Im getting an empty result (which isnt null). Those are two of the "working" queries:

select ?x from <localhost:7474> where { graph ?g { ?x ?y ?z } } 
select ?x where { graph ?g { ?x <http://localhost:7474#knows> ?z } } 

我仍然没有得到任何结果.

I still dont get any results.

推荐答案

我正在运行4节点群集. ClassNotFoundException的修复非常简单.

I am running 4 node cluster. The fix for ClassNotFoundException is very simple.

  1. 您复制的gremlin插件文件夹包含blueprints-core和blueprints-neo4j-graph的旧版本(1.2).删除gremlin插件目录下的那些旧库.

  1. The gremlin plugin folder you copy contains older version (1.2) of blueprints-core and blueprints-neo4j-graph. Delete those old libraries under the gremlin plugin directory.

更新sparql插件项目的pom.xml以包括最新的蓝图库.触发一个Maven构建(MVN清洁包).现在将neo4j-sparql-plugin-0.2-SNAPSHOT-server-plugin.zip解压缩到gremlin目录中.确保您拥有最新的blueprints-neo4j-graph-2.3.0.jar.

Update pom.xml of sparql plugin project to include latest blueprint libraries. Trigger a maven build (mvn clean package). Now extract the neo4j-sparql-plugin-0.2-SNAPSHOT-server-plugin.zip into gremlin directory. Make sure you have latest blueprints-neo4j-graph-2.3.0.jar.

尝试

现在,您的API应该可以使用了,您可以将Neo4j视为成熟的三重存储.玩得开心!

Now your APIs should work and you can treat your Neo4j as a full fledged triplestore. Have fun!

这篇关于Neo4j SPARQL插件REST用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆