2014-11-28 2 views
0

주제가 꽤 많이 있습니다. 두 노드 사이의 유형과 관계를 만들고 싶습니다. 아주 똑 바른 앞으로, 사람은 생각할지도 모르다. 그러나 지난 주와 마찬가지로 나는 올바른 구문으로 고심하고 있습니다.java 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] -는> (ME)

크리스

답변

1

가 나는 문제를 발견했다.

저처럼 모든 초보자들에게는 비틀 거릴 수 있습니다. 트랜잭션 내에서 생성 된 두 노드 간의 관계를 만들려면 관계를 만들기 전에 트랜잭션을 커밋해야합니다!

인사말,

크리스

+0

나는 혼란 스러워요. 실제로 사이퍼가 실행 중입니까? Cypher 엔드 포인트와 반대되는 노드/rels의 REST 엔드 포인트에 대해 실행중인 것처럼 보입니다. 연결하는 노드를 추가 할 때 동일한 트랜잭션에서 관계를 추가 할 수 있습니다.이 대답은 약간 오해의 소지가 있습니다. –

+0

이 모든 작업은 tx-cypher 끝점에 대해 하나 또는 몇 개의 cypher 문으로 수행 할 수 있습니다. –