简体   繁体   English

java neo4j创建关系密码崩溃

[英]java neo4j creating relationship cypher crashes

the topic pretty much says it: I want to create a relationship with a type between two nodes. 该主题几乎可以这样说:我想在两个节点之间创建一种类型的关系。 Pretty straight forward, one might think. 可能会很直截了当。 But like so often in the last weeks, I struggle with the correct syntax. 但是像过去几周一样,我一直在努力寻找正确的语法。

What I'm doing right now is this: 我现在正在做的是这样的:

    public URI createRelationship(GraphNodeTypes sourceType, URI sourceNode, 
                            GraphNodeTypes targetType, URI targetNode,
        GraphRelationshipTypes relationshipType, String[] jsonAttributes) {
    URI relationShipLocation = null;

    String cypherArt = getNodeIdFromLocation(sourceNode)+"-[:"+relationshipType+"]->"+getNodeIdFromLocation(targetNode);

    logger.info("creating relationship ({}:{}) -[:{}]-> ({}:{})", 
                                    sourceType,
                                    getNodeIdFromLocation(sourceNode), 
                                    relationshipType,
                                    targetType,
                                    getNodeIdFromLocation(targetNode));

    try {
        URI finalUrl = new URI( sourceNode.toString() + "/relationships" );
        String cypherStatement = generateJsonRelationship( targetNode,
                                                            relationshipType, 
                                                            jsonAttributes );

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

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

        String responseEntity = response.getEntity(String.class).toString();
        int responseStatus = response.getStatus();

        logger.trace("POST to {} returned status code {}, returned data: {}",
                finalUrl, responseStatus,
                responseEntity);

        // first check if the http code was ok
        HttpStatusCodes httpStatusCodes = HttpStatusCodes.getHttpStatusCode(responseStatus);
        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 {
            JSONParser reponseParser = new JSONParser();
            Object responseObj = reponseParser.parse(responseEntity);
            JSONObject jsonResponseObj = responseObj instanceof JSONObject ?(JSONObject) responseObj : null;
            if(jsonResponseObj == null)
                throw new ParseException(0, "returned json object is null");

            //logger.trace("returned response object is {}", jsonResponseObj.toString());
            try {
                relationShipLocation = new URI((String)((JSONObject)((JSONArray)((JSONObject)((JSONArray)((JSONObject)((JSONArray)jsonResponseObj.get("results")).get(0)).get("data")).get(0)).get("rest")).get(0)).get("self"));
            } catch (Exception e) {
                logger.warn("CREATE RELATIONSHIP statement did not return a self object, returning null -- error was {}", e.getMessage());
                relationShipLocation = null;
            }
        }
    } catch (Exception e) {
        logger.error("could not create relationship ");
    }
    return relationShipLocation;
}

private static String generateJsonRelationship( URI endNode,
        GraphRelationshipTypes relationshipType, String[] jsonAttributes ) {
    StringBuilder sb = new StringBuilder();
    sb.append( "{ \"to\" : \"" );
    sb.append( endNode.toString() );
    sb.append( "\", " );

    sb.append( "\"type\" : \"" );
    sb.append( relationshipType.toString() );
    if ( jsonAttributes == null || jsonAttributes.length < 1 ){
        sb.append( "\"" );
    } else {
        sb.append( "\", \"data\" : " );
        for ( int i = 0; i < jsonAttributes.length; i++ ) {
            sb.append( jsonAttributes[i] );
            if ( i < jsonAttributes.length - 1 ){
                // Miss off the final comma
                sb.append( ", " );
            }
        }
    }

    sb.append( " }" );
    return sb.toString();
}

But as you can guess, it's not working. 但您可以猜到,它不起作用。 I get this error in my application log: 我在应用程序日志中收到此错误:

 INFO  Neo4JPersistence - creating relationship (POST:101) -[:BELONGS_TO]-> (SOCIALNETWORK:72)
 TRACE Neo4JPersistence - sending CREATE RELATIONSHIP cypher as { "to" : "http://localhost:7474/db/data/node/72", "type" : "BELONGS_TO" } to endpoint http://localhost:7474/db/data/node/101/relationships

The neo4j server log outputs this: neo4j服务器日志输出以下内容:

 11:15:57.278 [qtp683244938-387] WARN  o.e.jetty.servlet.ServletHandler - /db/data/node/101/relationships

org.neo4j.graphdb.NotFoundException: Node 101 not found org.neo4j.graphdb.NotFoundException:找不到节点101

BUT this node is created, successfully just some milliseconds before - I can see it in the neo4j browser. 但是这个节点已经创建,成功的时间是几毫秒前-我可以在neo4j浏览器中看到它。

(NEO4J) -[:LOST]-> (ME) (NEO4J)-[:Lost]->(ME)

Chris 克里斯

I found the problem. 我发现了问题。

For all beginners like me, that might stumble upon it: If you want to create a relationship between two nodes created within a transaction, you have to commit the transaction, BEFORE creating the relationship! 对于像我这样的所有初学者来说,可能会发现:在事务中创建的两个节点之间创建关系时,必须先创建事务,然后再创建关系!

Greetings, 问候,

Chris 克里斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM