java neo4j创建关系cypher崩溃

时间:2014-11-28 10:56:10

标签: java rest neo4j

主题几乎说明了:我想在两个节点之间创建一个类型的关系。人们可能会想,非常直截了当。但就像在过去几周经常发生的那样,我正在努力使用正确的语法。

我现在正在做的是:

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

但是你可以猜到,它不起作用。我在应用程序日志中收到此错误:

 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

neo4j服务器日志输出:

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

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

但是这个节点是在几毫秒之前成功创建的 - 我可以在neo4j浏览器中看到它。

(NEO4J) - [:LOST] - &gt; (ME)

克里斯

1 个答案:

答案 0 :(得分:1)

我发现了问题。

对于像我这样的所有初学者,可能偶然发现它:如果你想在事务中创建的两个节点之间建立关系,你必须在创建关系之前提交事务!

问候,

克里斯