org.neo4j.driver.v1.Record Java Examples

The following examples show how to use org.neo4j.driver.v1.Record. 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: CEnhancement.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private void enhanceTranslationUnit(Record record) {
	Node node = record.get("n").asNode();
	String fileName = record.get("f.fileName").asString();
	if(fileName.endsWith(".ast")) {
		fileName = fileName.replaceAll(".ast", "");
		if(!fileName.endsWith(".h")) {
			fileName = fileName + ".c";
		}
	}

	this.fileNameTranslationUnit = fileName;
	connector.executeWrite(
			"MATCH (n) WHERE ID(n) = " + node.id() + " SET n.name = '" + fileName + "', n.fqn = '" + fileName + "', n.hash = '" + createHash(fileName) + "'"
	);

}
 
Example #2
Source File: ExpandFlossNodes.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public static SubGraph run(String query, SubGraph searchResult1, SubGraph linkedSearchResult1,  ApiLocatorContext context){
    SubGraph r = new SubGraph();
    r.getNodes().addAll(searchResult1.getNodes());
    r.cost = searchResult1.cost;
    List<LuceneSearchResult> luceneSearchResults=context.getLuceneSearcher().query(query);
    luceneSearchResults.sort((LuceneSearchResult a, LuceneSearchResult b)->{
        Double aDist=new Double(dist(a.nodeSet,searchResult1.getNodes(),context));
        Double bDist=new Double(dist(b.nodeSet,searchResult1.getNodes(),context));
        return aDist.compareTo(bDist);
    });
    for (int i=0;i<3&&i<luceneSearchResults.size();i++) {
        r.getNodes().add(luceneSearchResults.get(i).id);
        for (long node:linkedSearchResult1.getNodes()){
            Session session=context.connection.session();
            StatementResult rs=session.run("match (a)-[r]-(b) where id(a)="+node+" and id(b)="+luceneSearchResults.get(i).id+" return id(r)");
            while (rs.hasNext()){
                Record item=rs.next();
                r.getEdges().add(item.get("id(r)").asLong());
            }
            session.close();
        }
    }
    return r;
}
 
Example #3
Source File: ExpandDocxNodes.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public static SubGraph run(SubGraph searchResult1, ApiLocatorContext context){
    SubGraph r = new SubGraph();
    r.getNodes().addAll(searchResult1.getNodes());
    r.cost = searchResult1.cost;
    for (long node : searchResult1.getNodes()) {
        Session session = context.connection.session();
        String stat = "match p=(n1)-[:" + CodeInDocxFileExtractor.API_EXPLAINED_BY + "]->(n2) where id(n1)=" + node + " unwind relationships(p) as r return id(r), id(startNode(r)), id(endNode(r))";
        StatementResult rs = session.run(stat);
        while (rs.hasNext()) {
            Record item=rs.next();
            long node1 = item.get("id(startNode(r))").asLong();
            long node2 = item.get("id(endNode(r))").asLong();
            long rel = item.get("id(r)").asLong();
            r.getNodes().add(node1);
            r.getNodes().add(node2);
            r.getEdges().add(rel);
        }
        session.close();
    }
    return r;
}
 
Example #4
Source File: Neo4jCypherInterpreter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public Map<String, String> getLabels(boolean refresh) {
  if (labels == null || refresh) {
    Map<String, String> old = labels == null ?
        new LinkedHashMap<String, String>() : new LinkedHashMap<>(labels);
    labels = new LinkedHashMap<>();
    StatementResult result = this.neo4jConnectionManager.execute("CALL db.labels()");
    Set<String> colors = new HashSet<>();
    while (result.hasNext()) {
      Record record = result.next();
      String label = record.get("label").asString();
      String color = old.get(label);
      while (color == null || colors.contains(color)) {
        color = Neo4jConversionUtils.getRandomLabelColor();
      }
      colors.add(color);
      labels.put(label, color);
    }
  }
  return labels;
}
 
Example #5
Source File: City2City.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private void calculateFloors(Node building) {
	Node position = connector.getPosition(building.id());
	double bHeight = building.get("height").asDouble();
	double bWidth = building.get("width").asDouble();
	double bLength = building.get("length").asDouble();
	double bPosX = position.get("x").asDouble();
	double bPosY = position.get("y").asDouble();
	double bPosZ = position.get("z").asDouble();
	StatementResult floors = connector.executeRead("MATCH (n)-[:CONTAINS]->(f:Floor) WHERE ID(n) = " + building.id() +
		" RETURN f");
	int floorNumberValue = connector.executeRead("MATCH (n)-[:CONTAINS]->(f:Floor) WHERE ID(n) = " + building.id() +
		" RETURN COUNT(f) as floorNumber").single().get("floorNumber").asInt();

	int floorCounter = 0;
	while (floors.hasNext()) {
		Record record = floors.next();
		long floor = record.get("f").asNode().id();
		floorCounter++;
		String statement = cypherSetBuildingSegmentAttributes(floor, bWidth * 1.1, bLength * 1.1,
			bHeight / (floorNumberValue + 2 ) * 0.80, floorColor);
		statement +=
			String.format("CREATE (n)-[:HAS]->(p:City:Position {x: %f, y: %f, z: %f})", bPosX,
				(bPosY - ( bHeight / 2) ) + bHeight / ( floorNumberValue + 2 ) * floorCounter, bPosZ);
		connector.executeWrite(statement);
	}
}
 
Example #6
Source File: RDElementsFactory.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
public RDElement createFromMethod(Record result, double height, double ringWidth, double ringWidthAD,
                                  double transparency, double minArea, String color) {
    long id = result.get("node").asNode().id();
    long typeID = result.get("tID").asLong();
    if (methodTypeMode) {
        if (result.get("node").asNode().hasLabel(Labels.Constructor.name())) {
            return new DiskSegment(id, typeID, height, transparency, minArea, color, result.get("line").asInt(0));
        } else {
            return new SubDisk(id, typeID, ringWidth, height, transparency, color);
        }
    } else {
        if (methodDisks) {
            return new SubDisk(id, typeID, ringWidthAD, height, transparency, color);
        } else {
            return new DiskSegment(id, typeID, height, transparency, minArea, color, result.get("line").asInt(0));
        }
    }
}
 
Example #7
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 #8
Source File: OpenCypherClientService.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> executeQuery(String query, Map<String, Object> parameters, GraphQueryResultCallback handler) {
    try (Session session = gremlinDriver.session()) {
        StatementResult result = session.run(query, parameters);
        long count = 0;
        while (result.hasNext()) {
            Record record = result.next();
            Map<String, Object> asMap = handleInternalNode(record.asMap());
            handler.process(asMap, result.hasNext());
            count++;
        }

        Map<String,String> resultAttributes = new HashMap<>();
        resultAttributes.put(NODES_CREATED, NOT_SUPPORTED);
        resultAttributes.put(RELATIONS_CREATED, NOT_SUPPORTED);
        resultAttributes.put(LABELS_ADDED, NOT_SUPPORTED);
        resultAttributes.put(NODES_DELETED, NOT_SUPPORTED);
        resultAttributes.put(RELATIONS_DELETED, NOT_SUPPORTED);
        resultAttributes.put(PROPERTIES_SET, NOT_SUPPORTED);
        resultAttributes.put(ROWS_RETURNED, String.valueOf(count));

        return resultAttributes;
    } catch (Exception ex) {
        throw new ProcessException(ex);
    }
}
 
Example #9
Source File: CityIT.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
@Test
void layoutAlgorithmClass() {
	Record result = connector.executeRead(
 		"MATCH (:Type {hash: 'ID_a81ef0e8a047d15d20f4cc7bc0a8fef658100aa2'})<-[:VISUALIZES]-(:Building)-[:HAS]->(position:Position) " + 
 		"RETURN position.x as x, position.y as y, position.z as z"
	).single();
    double x = result.get("x").asDouble();
    double y = result.get("y").asDouble();
    double z = result.get("z").asDouble();
    assertEquals(90.5, x);
 	assertEquals(12.0, y);
 	assertEquals(146.5, z);
}
 
Example #10
Source File: RDIT.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
@Test
void dataSorting() {
	Record result = connector.executeRead(
		"MATCH (segment:DiskSegment)-[:VISUALIZES]->(:Field {hash: 'ID_5be5ae42eb1bd217d8f987674d19652fc2ba19df'}) " +
		"RETURN segment.angle as angle, segment.anglePosition as anglePosition"
	).single();
	double anglePosition = result.get("anglePosition").asDouble();
	assertEquals(150.01639344262296, anglePosition);
}
 
Example #11
Source File: RDIT.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
@Test
void methodSorting() {
	Record result = connector.executeRead(
		"MATCH (segment:DiskSegment)-[:VISUALIZES]->(:Method {hash: 'ID_bfdf7b3da476584de47af84e759495ce14f31e46'}) " +
		"RETURN segment.anglePosition as anglePosition"
	).single();
	double anglePosition = result.get("anglePosition").asDouble();
	assertEquals(354.44000000000005, anglePosition);
}
 
Example #12
Source File: CityIT.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
@Test
void classMembers() {
	Record result = connector.executeRead(
	 	"MATCH (building:Building)-[:VISUALIZES]->(:Type {hash: 'ID_14c970c755ed96a4d3ab92e63887ac7ed2e90bc2'}) " + 
	 	"RETURN building.height as height, building.length as length, building.width as width"
	 ).single();
	double height = result.get("height").asDouble();
	double length = result.get("length").asDouble();
	double width = result.get("width").asDouble();
	assertEquals(39.0, height);
	assertEquals(10.0, length);
	assertEquals(10.0, width);
}
 
Example #13
Source File: Neo4jNode.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public static Neo4jNode get(long id, SnowGraphContext context){
    Neo4jNode node=null;
    Session session = context.getNeo4jBoltDriver().session();
    String stat = "match (n) where id(n)=" + id + " return id(n), labels(n)[0], n";
    StatementResult rs = session.run(stat);
    while (rs.hasNext()) {
        Record item=rs.next();
        node=new Neo4jNode(item.get("id(n)").asLong(),item.get("labels(n)[0]").asString());
        node.properties.putAll(item.get("n").asMap());
        node.properties.put("id",node.id);
        node.properties.put("label",node.label);
    }
    session.close();
    return node;
}
 
Example #14
Source File: Neo4jRelation.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public static List<Neo4jRelation> getNeo4jRelationList(long nodeId, SnowGraphContext context){
    List<Neo4jRelation> list=new ArrayList<>();
    Session session = context.getNeo4jBoltDriver().session();
    String stat = "match p=(n)-[r]-(x) where id(n)=" + nodeId + " return id(r), id(startNode(r)), id(endNode(r)), type(r)";
    StatementResult rs = session.run(stat);
    while (rs.hasNext()) {
        Record item=rs.next();
        list.add(new Neo4jRelation(item.get("id(startNode(r))").asLong(),item.get("id(endNode(r))").asLong(),item.get("id(r)").asLong(),item.get("type(r)").asString()));
    }
    session.close();
    return list;
}
 
Example #15
Source File: Neo4jRelation.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public static Neo4jRelation get(long rId, SnowGraphContext context){
    Neo4jRelation r=null;
    Session session = context.getNeo4jBoltDriver().session();
    String stat = "match p=(n)-[r]-(x) where id(r)=" + rId + " return id(r), id(startNode(r)), id(endNode(r)), type(r)";
    StatementResult rs = session.run(stat);
    while (rs.hasNext()) {
        Record item=rs.next();
        r=new Neo4jRelation(item.get("id(startNode(r))").asLong(),item.get("id(endNode(r))").asLong(),item.get("id(r)").asLong(),item.get("type(r)").asString());
    }
    session.close();
    return r;
}
 
Example #16
Source File: CityIT.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
@Test
void layoutAlgorithmPackage() {
	Record result = connector.executeRead(
		"MATCH (:Package {hash: 'ID_736ff4e8c509af97b93144e21132e8b6f9810a26'})<-[:VISUALIZES]-(:District)-[:HAS]->(position:Position) " + 
		"RETURN position.x as x, position.y as y, position.z as z"
	).single();
	double x = result.get("x").asDouble();
	double y = result.get("y").asDouble();
	double z = result.get("z").asDouble();
    assertEquals(88.0, x);
    assertEquals(4.5, y);
    assertEquals(88.0, z);
}
 
Example #17
Source File: ConnectCodeElements.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public static SubGraph run(SubGraph searchResult1, ApiLocatorContext context){
    SubGraph r = new SubGraph();
    r.getNodes().addAll(searchResult1.getNodes());
    r.cost = searchResult1.cost;
    Set<Long> flags = new HashSet<>();
    for (long seed1 : searchResult1.getNodes()) {
        if (flags.contains(seed1))
            continue;
        for (long seed2 : searchResult1.getNodes()) {
            if (seed1 == seed2)
                continue;
            if (flags.contains(seed2))
                continue;
            Session session = context.connection.session();
            String stat = "match p=shortestPath((n1)-[:" + codeRels + "*..10]-(n2)) where id(n1)=" + seed1 + " and id(n2)=" + seed2
                    + " unwind relationships(p) as r return id(startNode(r)), id(endNode(r)), id(r)";
            StatementResult rs = session.run(stat);
            while (rs.hasNext()) {
                Record item=rs.next();
                long node1 = item.get("id(startNode(r))").asLong();
                long node2 = item.get("id(endNode(r))").asLong();
                long rel = item.get("id(r)").asLong();
                r.getNodes().add(node1);
                r.getNodes().add(node2);
                r.getEdges().add(rel);
                flags.add(seed2);
            }
            session.close();
        }
        flags.add(seed1);
    }
    return r;
}
 
Example #18
Source File: StatefulTestBean.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public String addPerson() {
    Session session = driver.session();
    try {
        session.run("CREATE (a:Person {name:'Arthur', title:'King'})");
        StatementResult result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title");


        Record record = result.next();
        return record.toString();
    } finally {
        session.run("MATCH (a:Person) delete a");
        session.close();
    }
}
 
Example #19
Source File: StatefulTestBean.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public String addPersonClassInstanceInjection() {
    Session session = injectedDriver.session();
    try {
        session.run("CREATE (a:Person {name:'CDI', title:'King'})");
        StatementResult result = session.run("MATCH (a:Person) WHERE a.name = 'CDI' RETURN a.name AS name, a.title AS title");


        Record record = result.next();
        return record.toString();
    } finally {
        session.run("MATCH (a:Person) delete a");
        session.close();
    }
}
 
Example #20
Source File: NestedBean.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@TransactionAttribute(REQUIRES_NEW)
public String getPerson(String name) {
    Session session = injectedDriver.session();
    try {
        StatementResult result = session.run("MATCH (a:Person) WHERE a.name = '" + name + "' RETURN a.name AS name, a.title AS title");
        if (result.hasNext()) {
            Record record = result.next();
            return record.toString();
        }
        return name + " not found";
    }
    finally {
        session.close();
    }
}
 
Example #21
Source File: Neo4jCypherInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private Set<String> getTypes(boolean refresh) {
  if (types == null || refresh) {
    types = new HashSet<>();
    StatementResult result = this.neo4jConnectionManager.execute("CALL db.relationshipTypes()");
    while (result.hasNext()) {
      Record record = result.next();
      types.add(record.get("relationshipType").asString());
    }
  }
  return types;
}
 
Example #22
Source File: Neo4jBoltPersistReader.java    From streams with Apache License 2.0 5 votes vote down vote up
protected Optional<StreamsDatum> buildDatum(Record record) {
  ObjectNode objectNode;

  if( record != null ) {
    ObjectNode valueJson = null;
    Map<String, ObjectNode> valueJsons = record.asMap(neo4jObjectNodeFunction);
    if( valueJsons.size() == 1) {
      valueJson = valueJsons.get(valueJsons.keySet().iterator().next());
    }
    objectNode = PropertyUtil.getInstance(mapper).unflattenObjectNode(valueJson);
    return Optional.of(new StreamsDatum(objectNode));
  }

  return Optional.empty();
}
 
Example #23
Source File: Neo4jBoltPersistReader.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public StreamsResultSet readAll() {

  Session session = null;

  String query = config.getQuery();
  Map<String, Object> params = mapper.convertValue(config.getParams(), Map.class);

  try {
    session = client.client().session();
    Transaction transaction = session.beginTransaction();

    this.statementResult = client.client().session().beginTransaction().run(query, params);

    while( statementResult.hasNext()) {
      Record record = statementResult.next();
      Optional<StreamsDatum> datum = buildDatum(record);
      if( datum.isPresent()) {
        write(datum.get());
      }
    }

  } catch(Exception ex) {
    LOGGER.warn("Exception", ex);
  } finally {
    if( session != null ) {
      session.close();
    }
  }
  return readCurrent();

}
 
Example #24
Source File: Neo4jBoltPersistReader.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  try {
    while (reader.statementResult.hasNext()) {
      Record record = statementResult.next();
      Optional<StreamsDatum> datum = reader.buildDatum(record);
      if( datum.isPresent() ) {
        reader.write(datum.get());
      }
    }
  } finally {
    readerTaskFuture.complete(true);
  }
}
 
Example #25
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
public BoltContentHandler(StatementResult statementResult, ResultHandler rh) {
	if (statementResult != null)
		this.records = statementResult.list(); // don't use streaming mode
	else
		this.records = new ArrayList<Record>();
	this.reloaded = new Reloaded(rh.getDbAccess());
}
 
Example #26
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getColumns() {
	List<String> columns = new ArrayList<String>();
	if (this.records.size() > 0) {
		Record rec = this.records.get(0);
		columns.addAll(rec.keys());
	}
	return columns;
}
 
Example #27
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Override
public int getColumnIndex(String colKey) {
	if (this.records.size() > 0) {
		Record rec = this.records.get(0);
		int idx;
		try {
			idx = rec.index(colKey);
		} catch (NoSuchElementException e) {
			idx = -1;
		}
		return idx;
	}
	return -1;
}
 
Example #28
Source File: Neo4JCypherClientService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> executeQuery(String query, Map<String, Object> parameters, GraphQueryResultCallback handler) {
    try (Session session = neo4JDriver.session()) {
        StatementResult result = session.run(query, parameters);
        long count = 0;
        while (result.hasNext()) {
            Record record = result.next();
            Map<String, Object> asMap = handleInternalNode(record.asMap());
            handler.process(asMap, result.hasNext());
            count++;
        }

        ResultSummary summary = result.summary();
        SummaryCounters counters = summary.counters();

        Map<String,String> resultAttributes = new HashMap<>();
        resultAttributes.put(NODES_CREATED,String.valueOf(counters.nodesCreated()));
        resultAttributes.put(RELATIONS_CREATED,String.valueOf(counters.relationshipsCreated()));
        resultAttributes.put(LABELS_ADDED,String.valueOf(counters.labelsAdded()));
        resultAttributes.put(NODES_DELETED,String.valueOf(counters.nodesDeleted()));
        resultAttributes.put(RELATIONS_DELETED,String.valueOf(counters.relationshipsDeleted()));
        resultAttributes.put(PROPERTIES_SET, String.valueOf(counters.propertiesSet()));
        resultAttributes.put(ROWS_RETURNED, String.valueOf(count));

        return resultAttributes;
    } catch (Exception ex) {
        getLogger().error("", ex);
        throw new ProcessException(ex);
    }
}
 
Example #29
Source File: RDIT.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
@Test
void layoutAlgorithmPackage() {
	Record result = connector.executeRead(
		"MATCH (:Package {hash: 'ID_52a6b74381719655ffacf4d2c8c38a22d5581078'})<-[:VISUALIZES]-(:MainDisk)-[:HAS]->(position:Position) " + 
		"RETURN position.x as x, position.y as y, position.z as z").single();
	double x = result.get("x").asDouble();
	double y = result.get("y").asDouble();
	double z = result.get("z").asDouble();
    assertEquals(-2.576052, x);
    assertEquals(-12.33451, y);
    assertEquals(0, z);
}
 
Example #30
Source File: RDElementsFactory.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
public RDElement createFromField(Record result, double ringWidthAD, double height, double transparency, String color) {
    long id = result.get("node").asNode().id();
    long typeID = result.get("tID").asLong();
    if (methodTypeMode) {
        return new SubDisk(id, typeID, ringWidthAD, height, transparency, color);
    } else {
        if (dataDisks) {
            return new SubDisk(id, typeID, ringWidthAD, height, transparency, color);
        } else {
            return new DiskSegment(id, typeID, height, transparency, color);
        }
    }
}