java neo4j检查是否存在关系

时间:2014-12-01 17:36:20

标签: java rest neo4j cypher relationship

如果这是重复的话,请删除,尽管到目前为止我还没有找到答案。

我有一个应用程序,通过针对REST-API的cypher语句创建节点和关系。我使用以下代码创建关系:

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

我的问题是我想检查在创建它之前两个节点之间是否存在给定类型的给定关系。

有人能告诉我,如何查询关系???

对于节点,我做了这样的MATCH:

 MATCH  cypher {"statements": [ {"statement": "MATCH (p:SOCIALNETWORK {sn_id: 'TW'} ) RETURN p", "resultDataContents":["REST"]} ] } 

针对端点

 http://localhost:7474/db/data/transaction/<NUMBER>

我如何构造语句以检查关系,比如在节点6和5之间或其他什么?

提前致谢,

克里斯

2 个答案:

答案 0 :(得分:4)

您可能需要考虑通过密码执行此操作,并使用MERGE/ON CREATE/ON MATCH关键字。

例如,您可以执行以下操作:

create (a:Person {name: "Bob"})-[:knows]->(b:Person {name: "Susan"});

MATCH  (a:Person {name: "Bob"}), (b:Person {name: "Susan"}) 
MERGE (a)-[r:knows]->(b) 
ON CREATE SET r.alreadyExisted=false 
ON MATCH SET r.alreadyExisted=true 
RETURN r.alreadyExisted;

我在此处提供的此MATCH/MERGE查询将返回true或false,具体取决于该关系是否已存在。

此外,FWIW看起来像你用来通过StringBuilder对象积累JSON的代码可能很笨重且容易出错。有许多好的库,比如Google GSON,它们会为你做JSON,所以你可以创建JSON对象,数组,基元等等 - 然后让库担心将它正确地序列化为字符串。这往往会使你的代码更清晰,更易于维护,当你搞砸了你的JSON格式(我们都这样做)时,它比你积累这样的字符串更容易找到。

答案 1 :(得分:3)

在Java中

Relationship getRelationshipBetween(Node n1, Node n2) { // RelationshipType type, Direction direction
    for (Relationship rel : n1.getRelationships()) { // n1.getRelationships(type,direction)
       if (rel.getOtherNode(n1).equals(n2)) return rel;
    }
    return null;
}