Java Code Examples for org.neo4j.graphdb.Result#next()

The following examples show how to use org.neo4j.graphdb.Result#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: Neo4jLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testPersonCar() {
    graphDb.beginTx();
    Node car = graphDb.createNode(Label.label("Car"));
    car.setProperty("make", "tesla");
    car.setProperty("model", "model3");

    Node owner = graphDb.createNode(Label.label("Person"));
    owner.setProperty("firstName", "baeldung");
    owner.setProperty("lastName", "baeldung");

    owner.createRelationshipTo(car, RelationshipType.withName("owner"));

    Result result = graphDb.execute("MATCH (c:Car) <-[owner]- (p:Person) " +
            "WHERE c.make = 'tesla'" +
            "RETURN p.firstName, p.lastName");

    Map<String, Object> firstResult = result.next();
    Assert.assertEquals("baeldung", firstResult.get("p.firstName"));
}
 
Example 2
Source File: GraphApi.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
public Graph getEdges(RelationshipType type, boolean entail, long skip, long limit) {
  String query = "MATCH path = (start)-[r:" + type.name() + (entail ? "!" : "") + "]->(end) "
      + " RETURN path "
      // TODO: This slows down the query dramatically.
      // + " ORDER BY ID(r) "
      + " SKIP " + skip + " LIMIT " + limit;
  Graph graph = new TinkerGraph();
  TinkerGraphUtil tgu = new TinkerGraphUtil(graph, curieUtil);
  Result result;
  try {
    result = cypherUtil.execute(query);
    while (result.hasNext()) {
      Map<String, Object> map = result.next();
      Path path = (Path) map.get("path");
      tgu.addPath(path);
    }
  } catch (ArrayIndexOutOfBoundsException e) {
    // Return and empty graph if the limit is too high...
  }
  return graph;
}
 
Example 3
Source File: HyperGeometricAnalyzer.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
private Set<AnalyzerInnerNode> getCompleteSetNodes(AnalyzeRequest request) throws Exception {
  String query =
      "match (r)<-[:subClassOf*]-(n)" + request.getPath()
          + "(i) where id(r) = "
          + getNodeIdFromIri(request.getOntologyClass()) + " with n, i as t return t, count(distinct n)";
  //System.out.println(query);
  Result result2 = cypherUtil.execute(query);
  Set<AnalyzerInnerNode> allSubjects = new HashSet<>();
  while (result2.hasNext()) {
    Map<String, Object> map = result2.next();
    Long count = (Long) map.get("count(distinct n)");
    Long nodeId = ((Node) map.get("t")).getId();
    allSubjects.add(new AnalyzerInnerNode(nodeId, count));
    allSubjects.addAll(resolveToParents(nodeId, count));
  }
  return allSubjects;
}
 
Example 4
Source File: CypherUtil.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
Set<String> getEntailedRelationshipNames(Collection<String> parents) {
  Set<String> entailedTypes = new HashSet<>();
  for (String parent : parents) {
    entailedTypes.add(parent);
    Map<String, Object> params = new HashMap<>();
    params.put("iri", parent);
    try (Transaction tx = graphDb.beginTx()) {
      Result result =
          graphDb.execute("START parent=node:node_auto_index(iri={iri}) "
              + "MATCH (parent)<-[:subPropertyOf|equivalentProperty*]-(subProperty) "
              + "RETURN distinct subProperty.iri as subProperty", params);
      while (result.hasNext()) {
        Map<String, Object> map = result.next();
        entailedTypes.add((String) map.get("subProperty"));
      }
      tx.success();
    }
  }
  return entailedTypes;
}
 
Example 5
Source File: QuartileCalculator.java    From paprika with GNU Affero General Public License v3.0 6 votes vote down vote up
private Map calculeTresholds(Result result){
    Map<String, Double> res = new HashMap<>();
    //Only one result in that case
    while (result.hasNext())
    {
        Map<String,Object> row = result.next();
        //Sometime neo4J return a double or an int... With toString it's works in all cases
        double q1 = Double.valueOf(row.get("Q1").toString());
        double med = Double.valueOf(row.get("MED").toString());
        double q3 = Double.valueOf(row.get("Q3").toString());
        double high  = q3 + ( 1.5 * ( q3 - q1));
        double very_high  = q3 + ( 3 * ( q3 - q1));
        res.put("Q1",q1);
        res.put("Q3",q3);
        res.put("MED",med);
        res.put("HIGH (1.5)",high);
        res.put("VERY HIGH (3.0)",very_high);
    }
    return res;
}
 
Example 6
Source File: DeepGLIntegrationTest.java    From ml-models with Apache License 2.0 6 votes vote down vote up
@Test
public void write() throws Exception {

    String writeProperty = "'foo'";
    Result result = db.execute("CALL embedding.deepgl('Node', 'TYPE', {writeProperty: " + writeProperty + ", nodeFeatures:['prop1']})");

    while (result.hasNext()) {
        System.out.println("summary = " + result.next());
    }

    Result embeddings = db.execute("MATCH (n:Node) RETURN n.foo AS foo");
    while(embeddings.hasNext()) {
        Map<String, Object> row = embeddings.next();
        System.out.println("embeddings = " + Arrays.toString((double[])row.get("foo")));
    }
}
 
Example 7
Source File: QueryEngine.java    From paprika with GNU Affero General Public License v3.0 5 votes vote down vote up
public void resultToCSV(Result result, String csvSuffix) throws IOException {
    String name = csvPrefix+csvSuffix;
    FileWriter fw = new FileWriter(name);
    BufferedWriter writer = new BufferedWriter( fw );
    List<String> columns = result.columns();
    Object val;
    int i;
    int columns_size = columns.size()-1;
    for(i=0;i<columns_size;i++){
        writer.write(columns.get(i));
        writer.write(',');
    }
    writer.write(columns.get(i));
    writer.newLine();
    while ( result.hasNext()){
        Map<String,Object> row = result.next();
        for(i=0;i<columns_size;i++){
            val = row.get(columns.get(i));
            if(val != null){
                writer.write(val.toString());
                writer.write(',');
            }
        }
        val = row.get(columns.get(i));
        if(val != null){
            writer.write(val.toString());
        }
        writer.newLine();
    }
    writer.close();
    fw.close();
}
 
Example 8
Source File: Neo4jLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testCreateNode() {

    graphDb.beginTx();

    Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"})" +
            "RETURN baeldung");

    Map<String, Object> firstResult = result.next();
    Node firstNode = (Node) firstResult.get("baeldung");
    Assert.assertEquals(firstNode.getProperty("name"), "Baeldung");
}
 
Example 9
Source File: Neo4jLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testFindAndReturn() {
    graphDb.beginTx();

    graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
            "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
            "RETURN baeldung, tesla");

    Result result = graphDb.execute("MATCH (company:Company)-[:owns]-> (car:Car)" +
            "WHERE car.make='tesla' and car.model='modelX'" +
            "RETURN company.name");

    Map<String, Object> firstResult = result.next();
    Assert.assertEquals(firstResult.get("company.name"), "Baeldung");
}
 
Example 10
Source File: HeavyBroadcastReceiverQuery.java    From paprika with GNU Affero General Public License v3.0 5 votes vote down vote up
public void executeFuzzy(boolean details) throws CypherException, IOException {
        Result result;
        try (Transaction ignored = graphDatabaseService.beginTx()) {
            String query = "MATCH (c:Class{is_broadcast_receiver:true})-[:CLASS_OWNS_METHOD]->(m:Method{name:'onReceive'}) WHERE m.number_of_instructions > "+high_noi+" AND m.cyclomatic_complexity>"+high_cc+" return m.app_key as app_key,m.cyclomatic_complexity as cyclomatic_complexity, m.number_of_instructions as number_of_instructions";
            if(details){
                query += ",m.full_name as full_name";
            }
            result = graphDatabaseService.execute(query);
            List<String> columns = new ArrayList<>(result.columns());
            columns.add("fuzzy_value");
            int noi,cc;
            List<Map> fuzzyResult = new ArrayList<>();
            File fcf = new File(fclFile);
            //We look if the file is in a directory otherwise we look inside the jar
            FIS fis;
            if(fcf.exists() && !fcf.isDirectory()){
                fis = FIS.load(fclFile, false);
            }else{
                fis = FIS.load(getClass().getResourceAsStream(fclFile),false);
            }
            FunctionBlock fb = fis.getFunctionBlock(null);
            while(result.hasNext()){
                HashMap res = new HashMap(result.next());
                cc = (int) res.get("cyclomatic_complexity");
                noi = (int) res.get("number_of_instructions");
                if(cc >= veryHigh_cc && noi >= veryHigh_noi){
                    res.put("fuzzy_value", 1);
                }else {
                    fb.setVariable("cyclomatic_complexity",cc);
                    fb.setVariable("number_of_instructions",noi);
                    fb.evaluate();
                    res.put("fuzzy_value", fb.getVariable("res").getValue());
                }
                fuzzyResult.add(res);
                }
                queryEngine.resultToCSV(fuzzyResult,columns,"_HBR.csv");
        }
}
 
Example 11
Source File: SAKQuery.java    From paprika with GNU Affero General Public License v3.0 5 votes vote down vote up
public void executeFuzzy(boolean details) throws CypherException, IOException {
        Result result;
        try (Transaction ignored = graphDatabaseService.beginTx()) {
            String query = "MATCH (cl:Class) WHERE HAS(cl.is_interface) AND cl.number_of_methods > " + high + " RETURN cl.app_key as app_key,cl.number_of_methods as number_of_methods";
            if(details){
                query += ",cl.name as full_name";
            }
            result = graphDatabaseService.execute(query);
            List<String> columns = new ArrayList<>(result.columns());
            columns.add("fuzzy_value");
            int cc;
            List<Map> fuzzyResult = new ArrayList<>();
            File fcf = new File(fclFile);
            //We look if the file is in a directory otherwise we look inside the jar
            FIS fis;
            if(fcf.exists() && !fcf.isDirectory()){
                fis = FIS.load(fclFile, false);
            }else{
                fis = FIS.load(getClass().getResourceAsStream(fclFile),false);
            }
            FunctionBlock fb = fis.getFunctionBlock(null);
            while(result.hasNext()){
                HashMap res = new HashMap(result.next());
                cc = (int) res.get("number_of_methods");
                if(cc >= veryHigh){
                    res.put("fuzzy_value", 1);
                }else {
                    fb.setVariable("number_of_methods",cc);
                    fb.evaluate();
                    res.put("fuzzy_value", fb.getVariable("res").getValue());
                }
                fuzzyResult.add(res);
                }
                queryEngine.resultToCSV(fuzzyResult,columns,"_SAK.csv");
        }
}
 
Example 12
Source File: Neo4jLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testUpdate() {
    graphDb.beginTx();

    graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
            "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
            "RETURN baeldung, tesla");

    Result result = graphDb.execute("MATCH (car:Car)" +
            "WHERE car.make='tesla'" +
            " SET car.milage=120" +
            " SET car :Car:Electro" +
            " SET car.model=NULL" +
            " RETURN car");

    Map<String, Object> firstResult = result.next();
    Node car = (Node) firstResult.get("car");

    Assert.assertEquals(car.getProperty("milage"), 120L);
    Assert.assertEquals(car.getLabels(), Arrays.asList(Label.label("Car"), Label.label("Electro")));

    try {
        car.getProperty("model");
        Assert.fail();
    } catch (NotFoundException e) {
        // expected
    }
}
 
Example 13
Source File: TriangleCount.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
@Override
public void collectResult(Result result) {
    while (result.hasNext()) {
        Map<String, Object> row = result.next();
        long nodeid = (long) row.get("nodeid");
        long triangleCount = (long) row.get("triangleCount");
        this.triangleMap.put(nodeid, triangleCount);
    }
}
 
Example 14
Source File: CCQuery.java    From paprika with GNU Affero General Public License v3.0 5 votes vote down vote up
public void executeFuzzy(boolean details) throws CypherException, IOException {
        Result result;
        try (Transaction ignored = graphDatabaseService.beginTx()) {
            String query = "MATCH (cl:Class) WHERE cl.class_complexity > " + high + " RETURN cl.app_key as app_key, cl.class_complexity as class_complexity";
            if(details){
                query += ",cl.name as full_name";
            }
            result = graphDatabaseService.execute(query);
            List<String> columns = new ArrayList<>(result.columns());
            columns.add("fuzzy_value");
            int cc;
            List<Map> fuzzyResult = new ArrayList<>();
            File fcf = new File(fclFile);
            //We look if the file is in a directory otherwise we look inside the jar
            FIS fis;
            if(fcf.exists() && !fcf.isDirectory()){
                fis = FIS.load(fclFile, false);
            }else{
                fis = FIS.load(getClass().getResourceAsStream(fclFile),false);
            }
            FunctionBlock fb = fis.getFunctionBlock(null);
            while(result.hasNext()){
                HashMap res = new HashMap(result.next());
                cc = (int) res.get("class_complexity");
                if(cc >= veryHigh){
                    res.put("fuzzy_value", 1);
                }else {
                    fb.setVariable("class_complexity",cc);
                    fb.evaluate();
                    res.put("fuzzy_value", fb.getVariable("res").getValue());
                }
                fuzzyResult.add(res);
                }
                queryEngine.resultToCSV(fuzzyResult,columns,"_CC.csv");
        }
}
 
Example 15
Source File: Neo4jLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testCreateNodeAndLink() {
    graphDb.beginTx();

    Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
            "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
            "RETURN baeldung, tesla");

    Map<String, Object> firstResult = result.next();
    Assert.assertTrue(firstResult.containsKey("baeldung"));
    Assert.assertTrue(firstResult.containsKey("tesla"));
}
 
Example 16
Source File: HyperGeometricAnalyzer.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
private Set<AnalyzerInnerNode> resolveToParents(Long nodeId, Long count) {
  Set<AnalyzerInnerNode> innerNodeSet = new HashSet<>();
  String query = "match (n)<-[:subClassOf*]-(p) where id(n) = " + nodeId + " return p";
  Result result = cypherUtil.execute(query);
  while (result.hasNext()) {
    Map<String, Object> map = result.next();
    innerNodeSet.add(new AnalyzerInnerNode(((Node) map.get("p")).getId(), count));
  }
  return innerNodeSet;
}
 
Example 17
Source File: HyperGeometricAnalyzer.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
private Set<AnalyzerInnerNode> getSampleSetNodes(AnalyzeRequest request) throws Exception {
  Map<Long, AnalyzerInnerNode> sampleNodes = new HashMap<Long, AnalyzerInnerNode>();
  List<Long> sampleSetId = new ArrayList<>();
  for (String sample : request.getSamples()) {
    sampleSetId.add(getNodeIdFromIri(sample));
  }
  String query =
      "match (r)<-[:subClassOf*]-(n)" + request.getPath()
          + "(i) where id(n) in " + sampleSetId + " and id(r) = "
          + getNodeIdFromIri(request.getOntologyClass()) + " with n, i as t return t, count(distinct n)";
  //System.out.println(query);
  Result result = cypherUtil.execute(query);
  while (result.hasNext()) {
    Map<String, Object> map = result.next();
    Long count = (Long) map.get("count(distinct n)");
    Long nodeId = ((Node) map.get("t")).getId();
    sampleNodes.put(nodeId, new AnalyzerInnerNode(nodeId, count));
    for(AnalyzerInnerNode parentToAdd: resolveToParents(nodeId, count)){
      if(sampleNodes.containsKey(parentToAdd.getNodeId())){
        AnalyzerInnerNode existingNode = sampleNodes.get(parentToAdd.getNodeId());
        sampleNodes.put(existingNode.getNodeId(),new  AnalyzerInnerNode(existingNode.getNodeId(), existingNode.getCount() + parentToAdd.getCount()));
      }else{
        sampleNodes.put(parentToAdd.getNodeId(), parentToAdd);
      }
    }
  }
  return new HashSet<AnalyzerInnerNode>(sampleNodes.values());
}
 
Example 18
Source File: Neo4jDriver.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
public Collection<Neo4jMatch> runQuery(final RailwayQuery query, final String queryDefinition) throws IOException {
	final Collection<Neo4jMatch> results = new ArrayList<>();

	final Result executionResult = graphDb.execute(queryDefinition);
	while (executionResult.hasNext()) {
		final Map<String, Object> row = executionResult.next();
		results.add(Neo4jMatch.createMatch(query, row));
	}

	return results;
}
 
Example 19
Source File: HyperGeometricAnalyzer.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
private int getTotalCount(String ontologyClass) throws Exception {
  String query =
      "match (n)-[:subClassOf*]->(r) where id(r) = " + getNodeIdFromIri(ontologyClass)
          + " return count(*)";
  Result result3 = cypherUtil.execute(query);
  int totalCount = 0;
  while (result3.hasNext()) {
    Map<String, Object> map = result3.next();
    totalCount = ((Long) map.get("count(*)")).intValue();
  }
  return totalCount;
}
 
Example 20
Source File: OwlPostprocessor.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
public void processSomeValuesFrom() {
  logger.info("Processing someValuesFrom classes");
  try (Transaction tx = graphDb.beginTx()) {
    Result results =
        graphDb.execute("MATCH (n)-[relationship]->(svf:someValuesFrom)-[:property]->(p) "
            + "RETURN n, relationship, svf, p");
    while (results.hasNext()) {
      Map<String, Object> result = results.next();
      Node subject = (Node) result.get("n");
      Relationship relationship = (Relationship) result.get("relationship");
      Node svf = (Node) result.get("svf");
      Node property = (Node) result.get("p");
      for (Relationship r : svf.getRelationships(OwlRelationships.FILLER)) {
        Node object = r.getEndNode();
        String relationshipName =
            GraphUtil.getProperty(property, CommonProperties.IRI, String.class).get();
        RelationshipType type = RelationshipType.withName(relationshipName);
        String propertyUri =
            GraphUtil.getProperty(property, CommonProperties.IRI, String.class).get();
        Relationship inferred = subject.createRelationshipTo(object, type);
        inferred.setProperty(CommonProperties.IRI, propertyUri);
        inferred.setProperty(CommonProperties.CONVENIENCE, true);
        inferred.setProperty(CommonProperties.OWL_TYPE, relationship.getType().name());
      }
    }
    tx.success();
    tx.close();
  }
}