org.neo4j.driver.v1.StatementResult Java Examples

The following examples show how to use org.neo4j.driver.v1.StatementResult. 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: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataStruct(Node struct) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(struct:Struct) WHERE ID(struct) = " + struct.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependent =  connector.executeRead(
			"MATCH (struct:Struct)-[:DEPENDS_ON]->(type) WHERE ID(struct) = " + struct.id() + " RETURN type.hash");
	if(dependent.hasNext()){
		dependsOn = dependent.single().get("type.hash").asString();
	}

	return formatLine("id", struct.get("hash").asString()) +
			formatLine("qualifiedName", struct.get("fqn").asString()) +
			formatLine("name", struct.get("name").asString()) +
			formatLine("type", "Struct") +
			formatLine("belongsTo", belongsTo) +
			formatLine(dependsOn, dependsOn) +
			formatLine("filename", struct.get("fileName").asString());
}
 
Example #2
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 #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: 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 #5
Source File: Neo4jConnectionManager.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public StatementResult execute(String cypherQuery,
    InterpreterContext interpreterContext) {
  Map<String, Object> params = new HashMap<>();
  if (interpreterContext != null) {
    ResourcePool resourcePool = interpreterContext.getResourcePool();
    Set<String> keys = extractParams(cypherQuery, PROPERTY_PATTERN, REPLACE_CURLY_BRACKETS);
    keys.addAll(extractParams(cypherQuery, $_PATTERN, REPLACE_$));
    for (String key : keys) {
      Resource resource = resourcePool.get(key);
      if (resource != null) {
        params.put(key, resource.get());
      }
    }
  }
  LOGGER.debug("Executing cypher query {} with params {}", cypherQuery, params);
  StatementResult result;
  try (Session session = getSession()) {
    result = params.isEmpty()
          ? getSession().run(cypherQuery) : getSession().run(cypherQuery, params);
  }
  return result;
}
 
Example #6
Source File: Neo4jContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void shouldCopyDatabase() {
    try (
        Neo4jContainer neo4jContainer = new Neo4jContainer()
            .withDatabase(MountableFile.forClasspathResource("/test-graph.db"));
    ) {
        neo4jContainer.start();
        try (
            Driver driver = getDriver(neo4jContainer);
            Session session = driver.session()
        ) {
            StatementResult result = session.run("MATCH (t:Thing) RETURN t");
            assertThat(result.list().stream().map(r -> r.get("t").get("name").asString()))
                .containsExactlyInAnyOrder("Thing", "Thing 2", "Thing 3", "A box");
        }
    }
}
 
Example #7
Source File: QueryRunner.java    From neoprofiler with Apache License 2.0 6 votes vote down vote up
public Map<String,List<Object>> runQueryComplexResult(NeoProfiler parent, String query, String...columns) {
	HashMap<String,List<Object>> all = new HashMap<String,List<Object>>();
	
	List<Object> retvals = new ArrayList<Object>();
	System.out.println(query);
	Session s = parent.getDriver().session();
	try ( Transaction tx = s.beginTransaction()) {
		// log.info(query);
		StatementResult result = tx.run(query);
		
		while(result.hasNext()) {
			Map<String,Object> row = result.next().asMap();
			
			for(String col : columns) { 
				if(!all.containsKey(col)) all.put(col, new ArrayList<Object>());
				all.get(col).add(row.get(col));
			}
		}	
		
		tx.close();
	} finally {
		s.close();
	}
	
	return all;
}
 
Example #8
Source File: CypherHandlersIT.java    From rdf2neo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test {@link CyNodeLoadingHandler} to see if nodes are mapped from RDF and loaded into Neo4J
 */
@Test
public void testNodes () throws Exception
{
	try (	
		Driver neoDriver = GraphDatabase.driver( "bolt://127.0.0.1:7687", AuthTokens.basic ( "neo4j", "test" ) );
	)
	{
		Session session = neoDriver.session ( AccessMode.READ );
		StatementResult cursor = session.run ( "MATCH ( n:TestNode ) RETURN COUNT ( n ) AS ct" );
		Assert.assertEquals ( "Wrong count for TestNode", 2, cursor.next ().get ( "ct" ).asLong () );
		
		cursor = session.run ( "MATCH ( n:TestNode { iri:'" + iri ( "ex:2" ) + "'} ) RETURN properties ( n ) AS props" );
		assertTrue ( "ex:2 not returned!", cursor.hasNext () );
		
		Map<String, Object> map = cursor.next ().get ( "props" ).asMap ();
		assertEquals (  "Wrong property!", "another string", map.get ( "attrib3" ) );
	}
}
 
Example #9
Source File: RD2RD.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private ArrayList<SubDisk> createSubDisksList() {
    ArrayList<SubDisk> list = new ArrayList<>();
    StatementResult result =  connector.executeRead("MATCH (p)-[:CONTAINS]->(d:SubDisk)-[:VISUALIZES]->(element) "
            + "RETURN d.ringWidth AS ringWidth, d.height as height," +
            " d.size AS size, ID(d) AS id, ID(p) AS parentID, ID(element) AS visualizedID ORDER BY element.hash");
    result.forEachRemaining(d -> {
        long visualizedID = d.get("visualizedID").asLong();
        long parentID = d.get("parentID").asLong();
        long id = d.get("id").asLong();
        double ringWidth = d.get("ringWidth").asDouble();
        double height = d.get("height").asDouble();
        SubDisk disk = new SubDisk(visualizedID, parentID, id, ringWidth, height);
        list.add(disk);
        setPositionToPackages(disk);
    });
    return list;
}
 
Example #10
Source File: InsightsGraphDBHandler.java    From Insights with Apache License 2.0 6 votes vote down vote up
@Override
public StatementResult read(final String query)  throws DataDeleteException {
	deleteDetachKeywordValidation(query);
	try ( Session session = GraphDBConnection.getInstance().getDriver().session() )
       {
		StatementResult records = session.readTransaction( new TransactionWork<StatementResult>()
           {
               @Override
               public StatementResult execute( Transaction tx )
               {
                   return runQuery( tx,query );
               }
           } );
		
		return records;
       }
}
 
Example #11
Source File: QueryRunner.java    From neoprofiler with Apache License 2.0 6 votes vote down vote up
public Value runQuerySingleResult(NeoProfiler parent, String query, String columnReturn) {		
	Session s = parent.getDriver().session();

	try ( Transaction tx = s.beginTransaction()) {
		// log.info(query);
		StatementResult result = tx.run(query);
					
		if(result.hasNext()) {
			Value val = result.next().get(columnReturn);
			return val;
		}
		
		return null;
	} finally {
		s.close();
	}
}
 
Example #12
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnumValue(Node ev) {
	String belongsTo = "";
	StatementResult parent = connector.executeRead("MATCH (parent)-[:DECLARES]->(enumValue) WHERE ID(enumValue) = " + ev.id() 
		+ " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	return "\"id\":            \"" + ev.get("hash").asString() + "\"," +
			"\n" +
			"\"qualifiedName\": \"" + ev.get("fqn").asString() + "\"," +
			"\n" +
			"\"name\":          \"" + ev.get("name").asString() + "\"," +
			"\n" +
			"\"type\":          \"FAMIX.EnumValue\"," +
			"\n" +
			"\"belongsTo\":     \"" + belongsTo + "\"" +
			"\n";
}
 
Example #13
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnum(Node e) {
	String belongsTo = "";
	StatementResult parent = connector.executeRead("MATCH (parent)-[:DECLARES]->(enum) WHERE ID(enum) = " + e.id() 
		+ " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	return "\"id\":            \"" + e.get("hash").asString() + "\"," +
			"\n" +
			"\"qualifiedName\": \"" + e.get("fqn").asString() + "\"," +
			"\n" +
			"\"name\":          \"" + e.get("name").asString() + "\"," +
			"\n" +
			"\"type\":          \"FAMIX.Enum\"," +
			"\n" +
			"\"modifiers\":     \"" + getModifiers(e) + "\"," +
			"\n" +
			"\"belongsTo\":     \"" + belongsTo + "\"" +
			"\n";
}
 
Example #14
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String getFunctionSignature(Node function){
	String signature;
	String returnType = "";
	StatementResult returnTypeNodes =  connector.executeRead(
			 "MATCH (function:Function)-[:RETURNS]->(node) WHERE ID(function) = " + function.id() + " RETURN node");
	if(returnTypeNodes.hasNext()) {
		returnType += returnTypeNodes.single().get("node").asNode().get("name").asString();
	}
	if(!returnType.endsWith("*")){
		returnType += " ";
	}
	String functionName = function.get("name").asString();
	List<Node> parameterList = new ArrayList<>();
	 StatementResult parameters =  connector.executeRead(
			 "MATCH (function:Function)-[:HAS]->(node) WHERE ID(function) = " + function.id() + " RETURN node ORDER BY node.index");
	 while (parameters.hasNext()) {
	 	parameterList.add(parameters.next().get("node").asNode());
	 }
	//var parameterList = function.getRelationships(Direction.OUTGOING, Rels.HAS).map[endNode]
	//sort parameters according to their index
	//parameterList = parameterList.sortBy[p|p.getProperty("index", 0) as Integer]
	String parameter = getFunctionParameters(parameterList);
	signature = returnType + functionName + "(" + parameter + ")";
	return signature;
}
 
Example #15
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 #16
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnumValue(Node enumValue) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(enumValue:EnumConstant) WHERE ID(enumValue) = " + enumValue.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependent =  connector.executeRead(
			"MATCH (enumValue:EnumConstant)-[:DEPENDS_ON]->(type) WHERE ID(enumValue) = " + enumValue.id() + " RETURN type.hash");
	if(dependent.hasNext()){
		dependsOn = dependent.single().get("type.hash").asString();
	}

	return formatLine("id", enumValue.get("hash").asString()) +
			formatLine("qualifiedName", enumValue.get("fqn").asString()) +
			formatLine("name", enumValue.get("name").asString()) +
			formatLine("type", "EnumValue") +
			formatLine("belongsTo", belongsTo) +
			formatLine(dependsOn, dependsOn) +
			formatLine("filename", enumValue.get("fileName").asString());
}
 
Example #17
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataFunction(Node function) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(function:Function) WHERE ID(function) = " + function.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependentList = connector.executeRead(
			"MATCH (function:Function)-[:DEPENDS_ON]->(el) WHERE ID(function) = " + function.id() + " RETURN el");
	if(dependentList.hasNext()) {
		dependsOn = dependentList.single().get("el.hash").asString();
	}

	return formatLine("id", function.get("hash").asString()) +
			formatLine("qualifiedName", escapeHtml4(function.get("fqn").asString())) +
			formatLine("name", function.get("name").asString()) +
			formatLine("type", "FAMIX.Function") +
			formatLine("signature", getFunctionSignature(function)) +
			formatLine("calls", getCalls(function)) +
			formatLine("calledBy", getCalledBy(function)) +
			formatLine("accesses", getAccesses(function)) +
			formatLine("belongsTo", belongsTo) +
			formatLine("dependsOn", dependsOn) +
			formatEndline("filename", function.get("fileName").asString());
}
 
Example #18
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnum(Node enumNode) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(enum:Enum) WHERE ID(enum) = " + enumNode.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependent =  connector.executeRead(
			"MATCH (enum:Enum)-[:DEPENDS_ON]->(type) WHERE ID(enum) = " + enumNode.id() + " RETURN type.hash");
	if(dependent.hasNext()){
		dependsOn = dependent.single().get("type.hash").asString();
	}

	return formatLine("id", enumNode.get("hash").asString()) +
			formatLine("qualifiedName", enumNode.get("fqn").asString()) +
			formatLine("name", enumNode.get("name").asString()) +
			formatLine("type", "Enum") +
			formatLine("belongsTo", belongsTo) +
			formatLine(dependsOn, dependsOn) +
			formatLine("filename", enumNode.get("fileName").asString());
}
 
Example #19
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataNegation(Node negation) {
	String negated = "";
	try {
		StatementResult negations =  connector.executeRead(
				"MATCH (negation:Negation)-[:NEGATES]->(condition) WHERE ID(negation) = " + negation.id() + " RETURN condition.hash");
		if(negations.hasNext()) {
			negated = negations.single().get("condition.hash").asString();
		}
	} catch (Exception e) {
		negated = "";
	}

	return formatLine("id", negation.get("hash").asString()) +
			formatLine("type", "Negation") +
			formatEndline("negated", negated);
}
 
Example #20
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataUnion(Node union) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(union:Union) WHERE ID(union) = " + union.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependent =  connector.executeRead(
			"MATCH (union:Union)-[:DEPENDS_ON]->(type) WHERE ID(union) = " + union.id() + " RETURN type.hash");
	if(dependent.hasNext()){
		dependsOn = dependent.single().get("type.hash").asString();
	}

	return formatLine("id", union.get("hash").asString()) +
			formatLine("qualifiedName", union.get("fqn").asString()) +
			formatLine("name", union.get("name").asString()) +
			formatLine("type", "Union") +
			formatLine("belongsTo", belongsTo) +
			formatLine(dependsOn, dependsOn) +
			formatLine("filename", union.get("fileName").asString());
}
 
Example #21
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 #22
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 #23
Source File: C2JSON.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
private String getFunctionParameters(Iterable<Node> parameterList){
	StringBuilder parameters = new StringBuilder();
	int counter = 0;
	for(Node parameter: parameterList){
		//add comma after parameter
		if(counter != 0){
			parameters.append(", ");
		}
		StringBuilder parameterTypeString = new StringBuilder();
		StatementResult parameterTypeList =  connector.executeRead(
				"MATCH (parameter:Parameter)-[:OF_TYPE]->(type:Type) WHERE ID(parameter) = " + parameter.id() + " RETURN type");
		while(parameterTypeList.hasNext()) {
			parameterTypeString.append(parameterTypeList.next().get("type").asNode().get("name").asString());
		}

		//put [] after the parameter name
		if(parameterTypeString.toString().endsWith("]")){
			String[] parts = parameterTypeString.toString().split("\\[", 2);
			log.info("string");
			log.info("parameterTypeString");
			log.info(parts[0]);
			parameters.append(parts[0]).append(parameter.get("name").asString()).append("[").append(parts[1]);
		} else {
			parameters.append(parameterTypeString).append(" ").append(parameter.get("name").asString());
		}
		counter++;
	}

	return parameters.toString();
}
 
Example #24
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 #25
Source File: ApiLocator.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public SubGraph query(String queryString) {

        if (queryString.matches("^[\\d\\s]+$")){ // 只有结点id构成的query
            List<Long> idList=new ArrayList<>();
            String[] eles = queryString.trim().split("\\s+");
            for (String e:eles)
                if (e.length()>0) {
                    Session session = context.connection.session();
                    long id=Long.parseLong(e);
                    String stat="match (n) where id(n)="+id+" return id(n)";
                    StatementResult rs = session.run(stat);
                    if (rs.hasNext()) {
                        idList.add(id);
                    }
                    session.close();
                }
            return idTest(idList);
        }

        /*
         * seedMap: - key: 定位到的代码元素结点的集合 - value: 这个集合的离散度,离散度越低,说明这个图的质量越好
		 */
        candidateMap.clear();// 清空candidateMap, 对于每个query即时生成
        scoreMap.clear();
        List<SubGraph> graphs = myFindSubGraphs(queryString);
        if (graphs.size() > 0) {
            if (debug)
                printGraphList(graphs);
            return graphs.get(0);
        }
        return new SubGraph();
    }
 
Example #26
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 #27
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 #28
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 #29
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 #30
Source File: ResultHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
/**
 * construct a ResultHandler initialized with a statementResult
 * @param statementResult
 * @param dbAccess
 */
public ResultHandler(StatementResult statementResult, IDBAccess dbAccess) {
	super();
	init(dbAccess);
	this.contentHandler = new BoltContentHandler(statementResult, this);
	
}