Java Code Examples for org.neo4j.driver.v1.StatementResult#next()

The following examples show how to use org.neo4j.driver.v1.StatementResult#next() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
Source File: LuceneSearcher.java    From SnowGraph with Apache License 2.0 4 votes vote down vote up
public void index(boolean overWrite) throws IOException {

        if (!overWrite && new File(path).exists())
            return;

        Directory dir = FSDirectory.open(Paths.get(path));
        Analyzer analyzer = new EnglishAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        iwc.setOpenMode(OpenMode.CREATE);
        IndexWriter writer = new IndexWriter(dir, iwc);

        Session session = context.connection.session();
        String stat = "match (n) where exists(n." + TextExtractor.IS_TEXT + ") and n." + TextExtractor.IS_TEXT + "=true return id(n), labels(n)[0], n." + TextExtractor.TITLE + ", n." + TextExtractor.TEXT;
        StatementResult rs = session.run(stat);
        int c=0;
        while (rs.hasNext()) {
            Record item = rs.next();
            String label=item.get("labels(n)[0]").asString();
            if (!(label.equals(StackOverflowExtractor.QUESTION)||label.equals(StackOverflowExtractor.ANSWER)||label.equals(JiraExtractor.ISSUE)))
                continue;
            String org_content = item.get("n." + TextExtractor.TEXT).asString();
            String title = item.get("n." + TextExtractor.TITLE).asString();
            String content = dealWithDocument("<html><title>" + title + "</title>" + org_content + "</html>");
            if (content.length() > 0) {
                Document document = new Document();
                long id=item.get("id(n)").asLong();
                document.add(new StringField("id", "" + id, Field.Store.YES));
                document.add(new StringField("type", item.get("labels(n)[0]").asString(), Field.Store.YES));
                document.add(new StringField("title", title, Field.Store.YES));
                document.add(new TextField("content", content, Field.Store.YES));
                document.add(new TextField("org_content", org_content, Field.Store.YES));
                Set<Long> nodes=new HashSet<>();
                Session session1=context.connection.session();
                StatementResult rs1=session1.run("match (a)-[:"+ ApiMentionExtractor.API_NAME_MENTION+"|"+ ReferenceExtractor.REFERENCE+"]->(b) where id(a)="+id+" and exists(b."+ LINEExtractor.LINE_VEC+") return distinct id(b)");
                while (rs1.hasNext()){
                    Record item1=rs1.next();
                    nodes.add(item1.get("id(b)").asLong());
                }
                session1.close();
                String nodeSet = StringUtils.join(nodes, " ").trim();
                document.add(new StringField("node_set", nodeSet, Field.Store.YES));
                writer.addDocument(document);
                System.out.println(c+": "+nodes.size());
                c++;
            }
        }
        session.close();

        writer.close();
    }
 
Example 16
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 17
Source File: ApiLocator.java    From SnowGraph with Apache License 2.0 4 votes vote down vote up
public SubGraph queryExpand(String queryString) {
    SubGraph r = new SubGraph();
    SubGraph searchResult1 = query(queryString);
    r.nodes.addAll(searchResult1.nodes);
    r.cost = searchResult1.cost;

    Set<Long> selected = new HashSet<>();
    selected.add(r.nodes.iterator().next());
    int rootCount = searchResult1.nodes.size() - 1;

    while(rootCount-- > 0){
        int minStep = Integer.MAX_VALUE;
        long candidate = 0;
        SubGraph path = null;
        for (long seed1 : selected){
            for (long seed2: searchResult1.nodes){
                if (selected.contains(seed2))
                    continue;
                SubGraph currentPath = new SubGraph();
                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();
                    currentPath.nodes.add(node1);
                    currentPath.nodes.add(node2);
                    currentPath.edges.add(rel);
                }
                session.close(); // may have no path
                if (currentPath.edges.size() > 0 && currentPath.edges.size() < minStep){
                    minStep = currentPath.edges.size();
                    path = currentPath;
                    candidate = seed2;
                }
            }

        }
        if (path == null) // cannot expand to other nodes
            break;
        selected.add(candidate);
        r.nodes.addAll(path.nodes);
        r.edges.addAll(path.edges);
    }
    if(debug)
        System.out.println("expanded graph size: " + r.nodes.size()+"\n");
    return r;
}
 
Example 18
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;
}