【问题标题】:java neo4j check if a relationship existjava neo4j 检查关系是否存在
【发布时间】:2015-01-29 18:54:56
【问题描述】:

排除这是否是重复的,虽然我到目前为止还没有找到答案。

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

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 之间的关系或其他关系?

提前致谢,

克里斯

【问题讨论】:

    标签: java rest neo4j cypher relationship


    【解决方案1】:

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

    【讨论】:

    • 嗨迈克尔,这个手术对我来说很重要。我经常尝试做的是仅在两个节点之间不存在时才创建关系。是否有可能以某种方式将此操作包含在 neo4j api 本身中,或者是否已经以某种方式包含“如果它不存在则创建”?
    【解决方案2】:

    您可能需要考虑通过密码执行此操作,并使用 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 查询将返回真或假,具体取决于关系是否已经存在。

    此外,FWIW 看起来您用于通过 StringBuilder 对象累积 JSON 的代码可能很笨重且容易出错。有很多像 Google GSON 这样的优秀库会为您处理 JSON,因此您可以创建 JSON 对象、数组、原语等——然后让库担心将其正确序列化为字符串。这往往会使您的代码更简洁,更易于维护,并且当您弄乱了 JSON 格式(我们都这样做)时,它比累积字符串时更容易找到。

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2014-08-24
      • 2014-01-15
      • 2020-05-14
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多