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

The following examples show how to use org.neo4j.graphdb.Result#hasNext() . 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: 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 2
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 3
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 4
Source File: QueryEngine.java    From paprika with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<String> findKeysFromPackageName(String appName) throws CypherException, IOException {
    ArrayList<String> keys = new ArrayList<>();
    try (Transaction ignored = graphDatabaseService.beginTx()) {
        Result result = graphDatabaseService.execute("MATCH (n:App) WHERE n.package='"+appName+"' RETURN n.app_key as key");
        while ( result.hasNext() )
        {
            Map<String,Object> row = result.next();
            keys.add((String) row.get("key"));
        }
    }
    return keys;
}
 
Example 5
Source File: Neo4j.java    From SPADE with GNU General Public License v3.0 6 votes vote down vote up
public List<Map<String, Object>> executeQueryForSmallResult(String query){
		try(Transaction tx = graphDb.beginTx()){
			List<Map<String, Object>> listOfMaps = new ArrayList<Map<String, Object>>();
			Result result = null;
//			globalTxCheckin();
			try{
				result = graphDb.execute(query);
				while(result.hasNext()){
					listOfMaps.add(new HashMap<String, Object>(result.next()));
				}
			}catch(QueryExecutionException ex){
				logger.log(Level.SEVERE, "Neo4j Cypher query execution not successful!", ex);
			}finally{
				tx.success();
			}
			return listOfMaps;
		}
	}
 
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: 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 8
Source File: BLOBQuery.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.lack_of_cohesion_in_methods >" + high_lcom + " AND cl.number_of_methods > " + high_nom + " AND cl.number_of_attributes > " + high_noa + " RETURN cl.app_key as app_key,cl.lack_of_cohesion_in_methods as lack_of_cohesion_in_methods,cl.number_of_methods as number_of_methods, cl.number_of_attributes as number_of_attributes";
            if(details){
                query += ",cl.name as full_name";
            }
            result = graphDatabaseService.execute(query);
            List<String> columns = new ArrayList<>(result.columns());
            columns.add("fuzzy_value");
            int lcom,noa,nom;
            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());
                lcom = (int) res.get("lack_of_cohesion_in_methods");
                noa = (int) res.get("number_of_attributes");
                nom = (int) res.get("number_of_methods");
                if(lcom >= veryHigh_lcom && noa >= veryHigh_noa && nom >= veryHigh_nom){
                    res.put("fuzzy_value", 1);
                }else {
                    fb.setVariable("lack_of_cohesion_in_methods",lcom);
                    fb.setVariable("number_of_attributes",noa);
                    fb.setVariable("number_of_methods",nom);
                    fb.evaluate();
                    res.put("fuzzy_value", fb.getVariable("res").getValue());
                }
                fuzzyResult.add(res);
                }
                queryEngine.resultToCSV(fuzzyResult,columns,"_BLOB.csv");
        }
}
 
Example 9
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 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: LMQuery.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 (m:Method) WHERE m.number_of_instructions >" + high + " RETURN m.app_key as app_key,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 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_instructions");
                if(cc >= veryHigh){
                    res.put("fuzzy_value", 1);
                }else {
                    fb.setVariable("number_of_instructions",cc);
                    fb.evaluate();
                    res.put("fuzzy_value", fb.getVariable("res").getValue());
                }
                fuzzyResult.add(res);
                }
                queryEngine.resultToCSV(fuzzyResult,columns,"_LM.csv");
        }
}
 
Example 13
Source File: TinkerGraphUtil.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
public Graph resultToGraph(Result result) {
  graph = new TinkerGraph();
  while (result.hasNext()) {
    Map<String, Object> map = result.next();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
      Object value = entry.getValue();
      String key = entry.getKey();
      if (null == value) {
        continue;
      } else if (value instanceof PropertyContainer) {
        addElement((PropertyContainer) value);
      } else if (value instanceof Path) {
        for (PropertyContainer container : (Path) value) {
          addElement(container);
        }
      } else if (value instanceof ArrayList) {
        for (Object thing : (ArrayList<?>) value) {
          if (thing instanceof PropertyContainer) {
            addElement((PropertyContainer) thing);
          }
        }
      } else if (value instanceof Boolean) {
        // generates a lonely node which contains the result
        Vertex vertex = graph.addVertex(key);
        vertex.setProperty(key, value);
        vertex.setProperty(NodeProperties.LABEL, "Boolean result");
        vertex.setProperty(CommonProperties.IRI, key);
      } else {
        logger.warning("Not converting " + value.getClass() + " to tinker graph");
      }
    }
  }
  return graph;
}
 
Example 14
Source File: DeepGLIntegrationTest.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Test
public void removeInnerLoopInPruning() throws Exception {

    Result result = db.execute("CALL embedding.deepgl('Node', 'TYPE', {pruningLambda: 0.8, iterations: 3})");

    while (result.hasNext()) {
        System.out.println("result.next() = " + result.next());
    }
}
 
Example 15
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 16
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();
  }
}
 
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: DeepGLIntegrationTest.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Test
public void stream() throws Exception {

    Result result = db.execute("CALL embedding.deepgl.stream('Node', 'TYPE')");

    while (result.hasNext()) {
        System.out.println("result.next() = " + result.next());
    }
}
 
Example 19
Source File: EdgeLabeler.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
  logger.info("Starting edge labeling...");
  Map<String, String> map = new HashMap<String, String>();
  int processedRels = 0;

  Transaction tx = graphDb.beginTx();
  ResourceIterable<Relationship> rels = graphDb.getAllRelationships();

  for (Relationship rel : rels) {

    if (processedRels % batchCommitSize == 0) {
      tx.success();
      tx.close();
      tx = graphDb.beginTx();
    }

    String relName = rel.getType().name();
    if (map.containsKey(relName)) {
      rel.setProperty(edgeProperty, map.get(relName));
    } else {
      String relLabel = relName;
      String query = "START n = node:node_auto_index(iri='" + relName + "') match (n) return n";
      Result result = graphDb.execute(query);
      if (result.hasNext()) {
        Node n = (Node) result.next().get("n");
        if (n.hasProperty(NodeProperties.LABEL)) {
          relLabel =
              GraphUtil.getProperties(n, NodeProperties.LABEL, String.class).iterator().next();
        }
      }
      rel.setProperty(edgeProperty, relLabel);
      map.put(relName, relLabel);
    }

    processedRels++;
  }

  logger.info(processedRels + " relations labeled.");
  tx.success();
  tx.close();
}
 
Example 20
Source File: GraphManagerTest.java    From graphify with Apache License 2.0 4 votes vote down vote up
private static String executeCypher(GraphDatabaseService db, String cypher, Map<String, Object> params) {

        Result result;

        List<Map<String, Object>> results = new ArrayList<>();

        try ( Transaction tx = db.beginTx() ) {
            result = db.execute(cypher, params);
            tx.success();



            while (result.hasNext()) {
                results.add(result.next());
            }

            tx.success();
            tx.close();
        }

        return new Gson().toJson(results);
    }