org.neo4j.driver.v1.types.Relationship Java Examples

The following examples show how to use org.neo4j.driver.v1.types.Relationship. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RelationshipProcedureTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateTheRelationshipAndTheNewCurrentStateBetweenEntities() throws Throwable {

    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {

        // Given
        Node entityA = initEntity(session);
        Node entityB = initEntity(session);
        String testType = "testType";

        // When
        String query = "MATCH (a:Entity), (b:Entity) WHERE id(a) = %d AND id(b) = %d WITH a, b CALL graph.versioner.relationship.create(a, b, '%s') YIELD relationship RETURN relationship";
        Relationship relationship = session.run(String.format(query, entityA.id(), entityB.id(), testType)).single().get("relationship").asRelationship();

        // Then
        String querySourceCurrent = "MATCH (e:Entity)-[:CURRENT]-(s:State) WHERE id(e) = %d RETURN s";
        String queryDestinationR = "MATCH (e:Entity)<-[:FOR]-(r:R) WHERE id(e) = %d RETURN r";
        Node sourceCurrent = session.run(String.format(querySourceCurrent, entityA.id())).single().get("s").asNode();
        Node destinationR = session.run(String.format(queryDestinationR, entityB.id())).single().get("r").asNode();
        Relationship expected = new InternalRelationship(0L, sourceCurrent.id(), destinationR.id(), testType);

        assertThat(relationship).isEqualToIgnoringGivenFields(expected, "id");
    }
}
 
Example #2
Source File: RelationshipProcedureTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateTheRelationshipAssociatedToANewStateHavingRequestedDate() {

    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {

        // Given
        Node entityA = initEntity(session);
        Node entityB = initEntity(session);
        String testType = "testType";
        Long date = 593920000000L;

        // When
        String query = "MATCH (a:Entity), (b:Entity) WHERE id(a) = %d AND id(b) = %d WITH a, b CALL graph.versioner.relationship.create(a, b, '%s', {}, localdatetime('1988-10-27T02:46:40')) YIELD relationship RETURN relationship";
        session.run(String.format(query, entityA.id(), entityB.id(), testType));

        // Then
        String querySourceCurrent = "MATCH (e:Entity)-[r:CURRENT]->(:State)-[:%s]->(:R) WHERE id(e) = %d RETURN r";
        Relationship currentRelationship = session.run(String.format(querySourceCurrent, testType, entityA.id())).single().get("r").asRelationship();

        assertThat(currentRelationship)
                .matches(rel -> rel.containsKey("date") && rel.get("date").asLocalDateTime().equals(convertEpochToLocalDateTime(date)));
    }
}
 
Example #3
Source File: RelationshipProcedureTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateTheRelationshipInANewCurrentStatePreservingTheOldOne() {

    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {

        // Given
        Node entityA = initEntity(session);
        Node entityB = initEntity(session);
        String testType = "testType";
        Long entityACurrentId = session.run(String.format("MATCH (e:Entity)-[:CURRENT]->(s:State) WHERE id(e) = %d RETURN s", entityA.id())).single().get("s").asNode().id();

        // When
        String query = "MATCH (a:Entity), (b:Entity) WHERE id(a) = %d AND id(b) = %d WITH a, b CALL graph.versioner.relationship.create(a, b, '%s') YIELD relationship RETURN relationship";
        Relationship relationship = session.run(String.format(query, entityA.id(), entityB.id(), testType)).single().get("relationship").asRelationship();

        // Then
        String querySourceStates = "MATCH (:R)<-[r:%s]-(s1:State)-[:PREVIOUS]->(s2:State) WHERE id(r) = %d RETURN s1, s2";
        StatementResult result = session.run(String.format(querySourceStates, testType, relationship.id()));

        assertThat(result)
                .hasSize(1)
                .allMatch(r -> r.get("s1").asNode().id() != r.get("s2").asNode().id() && r.get("s2").asNode().id() == entityACurrentId);
    }
}
 
Example #4
Source File: Neo4jBoltPersistReader.java    From streams with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public ObjectNode apply(@Nullable Value value) {
  ObjectNode resultNode = null;
  if (value instanceof StringValue) {
    StringValue stringValue = (StringValue) value;
    String string = stringValue.asLiteralString();
    try {
      resultNode = mapper.readValue(string, ObjectNode.class);
    } catch (IOException ex) {
      LOGGER.error("IOException", ex);
    }
  } else if ( value instanceof NodeValue) {
    NodeValue nodeValue = (NodeValue) value;
    Node node = nodeValue.asNode();
    Map<String, Object> nodeMap = node.asMap();
    resultNode = PropertyUtil.getInstance(mapper).unflattenMap(nodeMap);
  } else if (value instanceof RelationshipValue) {
    RelationshipValue relationshipValue = (RelationshipValue) value;
    Relationship relationship = relationshipValue.asRelationship();
    Map<String, Object> relationshipMap = relationship.asMap();
    resultNode = PropertyUtil.getInstance(mapper).unflattenMap(relationshipMap);
  }
  return resultNode;
}
 
Example #5
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 6 votes vote down vote up
private Entity getPropertiesObject(long id, int rowIndex, ElemType typ) {
	Record rec = this.records.get(rowIndex);
	List<Pair<String, Value>> flds = rec.fields();
	for (Pair<String, Value> pair : flds) {
		if (typ == ElemType.NODE && pair.value() instanceof NodeValue) {
			Node nd = pair.value().asNode();
			if (nd.id() == id)
				return nd;
		} else if (typ == ElemType.RELATION && pair.value() instanceof RelationshipValue) {
			Relationship rel = pair.value().asRelationship();
			if (rel.id() == id)
				return rel;
		}
	}
	
	// element with id may not have been loaded
	return this.reloaded.getEntity(id, typ);
}
 
Example #6
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 6 votes vote down vote up
@Override
public PathInfo getPathInfo(String colKey) {
	PathInfo pathInfo = null;
	Value val;
	try {
		val = this.record.get(colKey);
	} catch (NoSuchRecordException e) {
		throw new RuntimeException("no result column: " + colKey);
	}
	String typName = val.type().name();
	if ("PATH".equals(typName)) {
		Path p = val.asPath();
		long startId = p.start().id();
		long endId = p.end().id();
		List<Long> relIds = new ArrayList<Long>();
		Iterator<Relationship> it = p.relationships().iterator();
		while(it.hasNext()) {
			Relationship rel = it.next();
			relIds.add(Long.valueOf(rel.id()));
		}
		pathInfo = new PathInfo(startId, endId, relIds, p);
	}
	return pathInfo;
}
 
Example #7
Source File: RelationshipProcedureTest.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateTwoRelationshipsInTwoDifferentStates() {

    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {

        // Given
        Node entityA = initEntity(session);
        Node entityB = initEntity(session);
        Node entityC = initEntity(session);
        String testType1 = "testType1";
        String testType2 = "testType2";

        // When
        String query = "MATCH (a:Entity), (b:Entity) WHERE id(a) = %d AND id(b) = %d WITH a, b CALL graph.versioner.relationship.create(a, b, '%s') YIELD relationship RETURN relationship";
        session.run(String.format(query, entityA.id(), entityB.id(), testType1));
        session.run(String.format(query, entityA.id(), entityC.id(), testType2));

        // Then
        String querySourceStates = "MATCH (e:Entity)-[:CURRENT]->(:State)-[r]->(:R) WHERE id(e) = %d RETURN r";
        Stream<Relationship> result = session.run(String.format(querySourceStates, entityA.id())).list().stream()
                .map(r -> r.get("r").asRelationship());

        Relationship expectedRelationship1 = new InternalRelationship(0L, 0L, 0L, testType1);
        Relationship expectedRelationship2 = new InternalRelationship(0L, 0L, 0L, testType2);

        assertThat(result)
                .hasSize(2)
                .usingElementComparatorOnFields("type")
                .containsExactlyInAnyOrder(expectedRelationship1, expectedRelationship2);
    }
}
 
Example #8
Source File: GetTest.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetCurrentPathByGivenEntity() {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // Given
        session.run("CREATE (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        session.run("MATCH (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'}) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-27T00:00:00')}]->(s)");
        Node entity = session.run("MATCH (e:Entity) RETURN e").single().get("e").asNode();
        Node state = session.run("MATCH (s:State) RETURN s").single().get("s").asNode();

        // When
        StatementResult result = session.run("MATCH (e:Entity) WITH e CALL graph.versioner.get.current.path(e) YIELD path RETURN path");

        Path current = result.single().get("path").asPath();
        Iterator<Relationship> relsIterator = current.relationships().iterator();
        Map<String, Object> rels = new HashMap<>();
        while (relsIterator.hasNext()) {
            Relationship support = relsIterator.next();
            rels.put(support.type(), support);
        }

        // Then
        assertThat(current.contains(entity), equalTo(true));
        assertThat(rels.containsKey(Utility.CURRENT_TYPE), equalTo(true));
        assertThat(current.contains(state), equalTo(true));
    }
}
 
Example #9
Source File: GetTest.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetAllStateNodesByGivenEntity() {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // Given
        session.run("CREATE (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        session.run("MATCH (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'}) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-27T00:00:00')}]->(s)");
        session.run("MATCH (e)-[hs:HAS_STATE]->(s) CREATE (e)-[:HAS_STATE {startDate: localdatetime('1988-10-26T00:00:00'), endDate: hs.startDate}]->(:State{key:'oldState'})");
        session.run("MATCH (s1:State {key:'oldState'}), (s2:State {key:'initialValue'}) CREATE (s1)<-[:PREVIOUS {date: localdatetime('1988-10-26T00:00:00')}]-(s2) ");
        Node entity = session.run("MATCH (e:Entity) RETURN e").single().get("e").asNode();
        Node stateNew = session.run("MATCH (s:State {key:'initialValue'}) RETURN s").single().get("s").asNode();
        Node stateOld = session.run("MATCH (s:State {key:'oldState'}) RETURN s").single().get("s").asNode();

        // When
        StatementResult result = session.run("MATCH (e:Entity) WITH e CALL graph.versioner.get.all(e) YIELD path RETURN path");

        Path current = result.single().get("path").asPath();
        Iterator<Relationship> relsIterator = current.relationships().iterator();
        Map<String, Object> rels = new HashMap<>();
        while (relsIterator.hasNext()) {
            Relationship support = relsIterator.next();
            rels.put(support.type(), support);
        }

        // Then
        assertThat(current.contains(entity), equalTo(true));
        assertThat(current.contains(stateNew), equalTo(true));
        assertThat(rels.containsKey(Utility.PREVIOUS_TYPE), equalTo(true));
        assertThat(current.contains(stateOld), equalTo(true));
    }
}
 
Example #10
Source File: GetTest.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetAllStateNodesByGivenEntityWithOnlyOneCurrentState() {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // Given
        session.run("CREATE (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        session.run("MATCH (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'}) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-27T00:00:00')}]->(s)");
        Node entity = session.run("MATCH (e:Entity) RETURN e").single().get("e").asNode();
        Node stateNew = session.run("MATCH (s:State {key:'initialValue'}) RETURN s").single().get("s").asNode();

        // When
        StatementResult result = session.run("MATCH (e:Entity) WITH e CALL graph.versioner.get.all(e) YIELD path RETURN path");

        Path current = result.single().get("path").asPath();
        Iterator<Relationship> relsIterator = current.relationships().iterator();
        Map<String, Object> rels = new HashMap<>();
        while (relsIterator.hasNext()) {
            Relationship support = relsIterator.next();
            rels.put(support.type(), support);
        }

        // Then
        assertThat(current.contains(entity), equalTo(true));
        assertThat(current.contains(stateNew), equalTo(true));
    }
}
 
Example #11
Source File: Neo4jCypherInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private InterpreterResult renderGraph(Set<Node> nodes,
    Set<Relationship> relationships) {
  logger.info("Executing renderGraph method");
  List<org.apache.zeppelin.tabledata.Node> nodesList = new ArrayList<>();
  List<org.apache.zeppelin.tabledata.Relationship> relsList = new ArrayList<>();
  for (Relationship rel : relationships) {
    relsList.add(Neo4jConversionUtils.toZeppelinRelationship(rel));
  }
  Map<String, String> labels = getLabels(true);
  for (Node node : nodes) {
    nodesList.add(Neo4jConversionUtils.toZeppelinNode(node, labels));
  }
  return new GraphResult(Code.SUCCESS,
      new GraphResult.Graph(nodesList, relsList, labels, getTypes(true), true));
}
 
Example #12
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Override
public String getRelationType(long relationId, int rowIndex) {
	if (rowIndex >= 0) {
		Relationship rel = (Relationship) getPropertiesObject(relationId, rowIndex, ElemType.RELATION);
		return rel.type();
	}
	return null;
}
 
Example #13
Source File: InsightsGraphDBHandler.java    From Insights with Apache License 2.0 4 votes vote down vote up
private List<InsightsGraphNode> getNodes(StatementResult result){
	List<InsightsGraphNode> insightNodes = new ArrayList<>();
	
	while(result.hasNext()) {
		Record record = result.next();
		Iterable<String> keys = record.keys();
		log.debug(keys);
		Iterator<String> keyItr = keys.iterator();
		Node node =  null;
		Relationship relation = null;
		InsightsGraphNode graphNode = new InsightsGraphNode();
		InsightsRelationShip nodeRelationShip = null;
		while(keyItr.hasNext()) {
			String key = keyItr.next();
			Object o = record.get(key);
			if(o instanceof NodeValue) {
				node = ((NodeValue)o).asNode();
				graphNode = new InsightsGraphNode();
				
				Iterable<String> nodeLabel = node.labels(); //.iterator()
				List<String> labelList =(List<String>) StreamSupport
						.stream(nodeLabel.spliterator(), false)
						.collect(Collectors.toList());
				
				log.debug(" labelList ==== "+labelList.toString()); 				
				graphNode.setLabels(labelList);
				graphNode.setPropertyMap(node.asMap());
				
				if(relation != null && node.id() == relation.startNodeId()) {
					graphNode.setRelation(nodeRelationShip);
					if(node != null && node.id() == relation.startNodeId()) {
						if(graphNode != null) {
							graphNode.setRelation(nodeRelationShip);
						}
						nodeRelationShip.setStartNode(graphNode);
					} else if (node != null && node.id() == relation.endNodeId()) {
						if(graphNode != null) {
							graphNode.setRelation(nodeRelationShip);
						}
						nodeRelationShip.setEndNode(graphNode);
					}
				}
				
			} else if (o instanceof RelationshipValue) {
				relation = ((RelationshipValue)o).asRelationship();
				
				nodeRelationShip = new InsightsRelationShip();
				nodeRelationShip.setPropertyMap(relation.asMap());
				nodeRelationShip.setName(relation.type());
				
				if(node != null && node.id() == relation.startNodeId()) {
					if(graphNode != null) {
						graphNode.setRelation(nodeRelationShip);
					}
					nodeRelationShip.setStartNode(graphNode);
				} else if (node != null && node.id() == relation.endNodeId()) {
					if(graphNode != null) {
						graphNode.setRelation(nodeRelationShip);
					}
					nodeRelationShip.setEndNode(graphNode);
				}
			}
			
		}
	}
	
	return insightNodes;
}
 
Example #14
Source File: Neo4jCypherInterpreter.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Override
public InterpreterResult interpret(String cypherQuery, InterpreterContext interpreterContext) {
  logger.info("Opening session");
  if (StringUtils.isBlank(cypherQuery)) {
    return new InterpreterResult(Code.SUCCESS);
  }
  try {
    StatementResult result = this.neo4jConnectionManager.execute(cypherQuery,
            interpreterContext);
    Set<Node> nodes = new HashSet<>();
    Set<Relationship> relationships = new HashSet<>();
    List<String> columns = new ArrayList<>();
    List<List<String>> lines = new ArrayList<List<String>>();
    while (result.hasNext()) {
      Record record = result.next();
      List<Pair<String, Value>> fields = record.fields();
      List<String> line = new ArrayList<>();
      for (Pair<String, Value> field : fields) {
        if (field.value().hasType(InternalTypeSystem.TYPE_SYSTEM.NODE())) {
          nodes.add(field.value().asNode());
        } else if (field.value().hasType(InternalTypeSystem.TYPE_SYSTEM.RELATIONSHIP())) {
          relationships.add(field.value().asRelationship());
        } else if (field.value().hasType(InternalTypeSystem.TYPE_SYSTEM.PATH())) {
          nodes.addAll(Iterables.asList(field.value().asPath().nodes()));
          relationships.addAll(Iterables.asList(field.value().asPath().relationships()));
        } else {
          setTabularResult(field.key(), field.value(), columns, line,
                  InternalTypeSystem.TYPE_SYSTEM);
        }
      }
      if (!line.isEmpty()) {
        lines.add(line);
      }
    }
    if (!nodes.isEmpty()) {
      return renderGraph(nodes, relationships);
    } else {
      return renderTable(columns, lines);
    }
  } catch (Exception e) {
    logger.error("Exception while interpreting cypher query", e);
    return new InterpreterResult(Code.ERROR, e.getMessage());
  }
}
 
Example #15
Source File: Neo4jConversionUtils.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
public static org.apache.zeppelin.tabledata.Relationship toZeppelinRelationship(Relationship r) {
  return new org.apache.zeppelin.tabledata.Relationship(r.id(), r.asMap(),
      r.startNodeId(), r.endNodeId(), r.type());
}