【问题标题】:create a node in neo4j graph db with transaction endpoint使用事务端点在 Neo4j 图形数据库中创建一个节点
【发布时间】:2014-11-18 08:20:40
【问题描述】:

我知道这可能被问了一百次,相信我,我已经在网上阅读了很多。但是,我绝对不适合这样做,所以我在这里急需帮助。

我想要做的是使用 cypher 和事务端点在 neo4j 数据库中创建一个带有标签和属性的节点 - 使用来自 json 的属性。

这是我目前的代码:

/**
 * 
 * @description creates a node in the graph 
 * @param       json object
 * @param       label
 * 
 */
private String createNodeObjectTransactional(JSONObject nodeObject, GraphNodeTypes label){
    String nodeLocation=null;
    try{
        dbServerUrl = "http://localhost:7474"
        transactionUrl = dbServerUrl + "/db/data" + "/transaction";
        String finalUrl = transactionUrl;

        String payload = "{\"statements\": [ {\"statement\": \"CREATE\" (p:"+ label.toString() +" "+ nodeObject.toString() + ") } ] }";

        logger.trace("sending cypher {} to endpoint {}", payload, finalUrl);
        WebResource resource = Client.create().resource( finalUrl );

        ClientResponse response = resource
                .accept( MediaType.APPLICATION_JSON )
                .type( MediaType.APPLICATION_JSON )
                .entity( payload )
                .post( ClientResponse.class );

        nodeLocation = response.getLocation().toString();

        String responseString = response.getEntity(String.class);

        logger.debug("POST to {} returned status code {}, returned data: {}",
                finalUrl, response.getStatus(),
                responseString);

        // first check if the http code was ok
        HttpStatusCodes httpStatusCodes = HttpStatusCodes.getHttpStatusCode(response.getStatus());
        if (!httpStatusCodes.isOk()){
            if (httpStatusCodes == HttpStatusCodes.FORBIDDEN){
                logger.error(HttpErrorMessages.getHttpErrorText(httpStatusCodes.getErrorCode()));
            } else {
                logger.error("Error {} sending data to {}: {} ", response.getStatus(), finalUrl, HttpErrorMessages.getHttpErrorText(httpStatusCodes.getErrorCode()));
            }
        } else {
            // now do the check on json details within the returned JSON object
            JSONParser reponseParser = new JSONParser();
            Object responseObj = reponseParser.parse(responseString);
            JSONObject jsonResponseObj = responseObj instanceof JSONObject ?(JSONObject) responseObj : null;
            if(jsonResponseObj == null)
                throw new ParseException(0, "returned json object is null");

            // this is the location to commit the transaction if node creation was successfull
            String commit = (String) jsonResponseObj.get("commit").toString();
            // this contains an error object (actually an array) in case the creation was NOT successfull
            String error = (String) jsonResponseObj.get("errors").toString();
            // doknow what that is
            String result = (String) jsonResponseObj.get("results").toString();

            final URI location = response.getLocation();

            if (error.isEmpty()) {
                logger.info("new node created at location {}", location);
                logger.trace("returned result json is {}", result.toString());
                logger.debug("committing transaction at location {}", commit);
                resource = Client.create().resource( commit );
                response = resource
                        .accept( MediaType.APPLICATION_JSON )
                        .type( MediaType.APPLICATION_JSON )
                        .post( ClientResponse.class );
                logger.debug("COMMIT returned status code {}, returned data: {}",
                        response.getStatus(),
                        response.getEntity(String.class));
            } else {
                logger.error("ERROR :: {} - could not create node at location {}", error.substring(13), location);
                logger.trace("returned error json is {}", error.toString());
            }
        }
        response.close();

    } catch(Exception e) {
        logger.error("EXCEPTION :: failed to create node - {}", e.getMessage());
        e.printStackTrace();
    }

    return nodeLocation;
}

这是服务器的响应:

ERROR :: Unable to deserialize request: Unexpected character ('(' (code 40)): was expecting comma to separate OBJECT entries\n at [Source: org.eclipse.jetty.server.HttpConnection$Input@44382113{HttpChannelOverHttp@41038962{r=6,a=DISPATCHED,uri=\/db\/data\/transaction},HttpConnection@4f30a246{FILLING},g=HttpGenerator{s=START},p=HttpParser{s=END,275 of 275}}; line: 1, column: 42]","code":"Neo.ClientError.Request.InvalidFormat"}] - could not create node at location http://localhost:7474/db/data/transaction/121

对此真正困扰我的是,在 neo4j 网站上给出的示例中,他们确实放入了 ( 字符来封装标签和 json 对象,但服务器不喜欢该字符。如答案中所述:

Unexpected character ('(' (code 40)): was expecting comma to separate OBJECT

我不知道服务器在此位置添加逗号意味着什么。它不在对象的儿子之内,而是在它之前。

跟踪日志来了:

INFO  Neo4JPersistence - creating a Twitter node object to store in the graph
DEBUG Neo4JPersistence - creating node transactional
TRACE Neo4JPersistence - sending cypher payload {"statements": [ {"statement": "CREATE" (p:POST {"id":"534621287264817153","subject":"daily....","teaser":"daily...","lang":"de","sn_id":"TW"}) } ] } to endpoint http://localhost:7474/db/data/transaction
DEBUG Neo4JPersistence - POST to http://localhost:7474/db/data/transaction returned status code 201, returned data: {"commit":"http://localhost:7474/db/data/transaction/121/commit","results":[],"transaction":{"expires":"Tue, 18 Nov 2014 08:19:55 +0000"},"errors":[{"code":"Neo.ClientError.Request.InvalidFormat","message":"Unable to deserialize request: Unexpected character ('(' (code 40)): was expecting comma to separate OBJECT entries\n at [Source: org.eclipse.jetty.server.HttpConnection$Input@44382113{HttpChannelOverHttp@41038962{r=6,a=DISPATCHED,uri=/db/data/transaction},HttpConnection@4f30a246{FILLING},g=HttpGenerator{s=START},p=HttpParser{s=END,275 of 275}}; line: 1, column: 42]"}]}
ERROR Neo4JPersistence - ERROR :: Unable to deserialize request: Unexpected character ('(' (code 40)): was expecting comma to separate OBJECT entries\n at [Source: org.eclipse.jetty.server.HttpConnection$Input@44382113{HttpChannelOverHttp@41038962{r=6,a=DISPATCHED,uri=\/db\/data\/transaction},HttpConnection@4f30a246{FILLING},g=HttpGenerator{s=START},p=HttpParser{s=END,275 of 275}}; line: 1, column: 42]","code":"Neo.ClientError.Request.InvalidFormat"}] - could not create node at location http://localhost:7474/db/data/transaction/121
TRACE Neo4JPersistence - returned error json is [{"message":"Unable to deserialize request: Unexpected character ('(' (code 40)): was expecting comma to separate OBJECT entries\n at [Source: org.eclipse.jetty.server.HttpConnection$Input@44382113{HttpChannelOverHttp@41038962{r=6,a=DISPATCHED,uri=\/db\/data\/transaction},HttpConnection@4f30a246{FILLING},g=HttpGenerator{s=START},p=HttpParser{s=END,275 of 275}}; line: 1, column: 42]","code":"Neo.ClientError.Request.InvalidFormat"}]

请,请,请,

谁能帮帮我?

提前致谢,

克里斯

【问题讨论】:

  • 向我们展示带有有效负载的跟踪日志。
  • 您好,感谢您的回复。我添加了跟踪日志 - 你能看到,我做错了什么吗?

标签: java neo4j cypher


【解决方案1】:

正如错误告诉你的那样,你传递的是格式错误的 json

... "CREATE" (p:POST ...

Json 应该和这里描述的一样

{
  "statements" : [ {
    "statement" : "CREATE (n {props}) RETURN n",
    "parameters" : {
      "props" : {
        "name" : "My Node"
      }
    }
  } ]
}

(详见docs

在你的情况下:

String payload = "{\"statements\": 
    [ {\"statement\": \"CREATE (p:"+ label.toString() +" " {props}) \", 
       \"parameters\":" + nodeObject.toString() + " } ] }";

【讨论】:

    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多