Java Code Examples for org.neo4j.driver.v1.Session#run()

The following examples show how to use org.neo4j.driver.v1.Session#run() . 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: Neo4JServerLiveTest.java    From tutorials with MIT License 12 votes vote down vote up
@Test
public void standAloneDriver() {
    Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "12345"));
    Session session = driver.session();

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

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

    Assert.assertTrue(result.hasNext());
    Assert.assertEquals(result.next().get("company.name").asString(), "Baeldung");

    session.close();
    driver.close();
}
 
Example 2
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 3
Source File: ExpandDocxNodes.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public static SubGraph run(SubGraph searchResult1, ApiLocatorContext context){
    SubGraph r = new SubGraph();
    r.getNodes().addAll(searchResult1.getNodes());
    r.cost = searchResult1.cost;
    for (long node : searchResult1.getNodes()) {
        Session session = context.connection.session();
        String stat = "match p=(n1)-[:" + CodeInDocxFileExtractor.API_EXPLAINED_BY + "]->(n2) where id(n1)=" + node + " unwind relationships(p) as r return id(r), id(startNode(r)), id(endNode(r))";
        StatementResult rs = session.run(stat);
        while (rs.hasNext()) {
            Record item=rs.next();
            long node1 = item.get("id(startNode(r))").asLong();
            long node2 = item.get("id(endNode(r))").asLong();
            long rel = item.get("id(r)").asLong();
            r.getNodes().add(node1);
            r.getNodes().add(node2);
            r.getEdges().add(rel);
        }
        session.close();
    }
    return r;
}
 
Example 4
Source File: 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 5
Source File: StatefulTestBean.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public String transactionEnlistmentReadAfterCallingTransactionClose() {
    // JTA transaction is started by CMT, the following obtains a Session that is enlisted into the JTA transaction.
    Session session = injectedDriver.session();
    // The only way to influence success/failure of the Neo4j + JTA transaction, is at the JTA transaction level.
    // If the JTA transaction fails, org.neo4j.driver.v1.Transaction.failure() is called.
    // If the JTA transaction succeeds, org.neo4j.driver.v1.Transaction.success() is called.
    // org.neo4j.driver.v1.Transaction.close() is also called when the JTA transaction ends.

    // Calls to Session.beginTransaction() in a JTA transaction are expected to throw a RuntimeException
    try {
        Transaction transaction = session.beginTransaction();
        fail("Calling Session.beginTransaction in a JTA transaction should throw a RuntimeException.");
    } catch (RuntimeException expectedException) {
        // success
    }

    try {
        session.run("CREATE (a:Person {name:'TRANSACTION', title:'King'})");
        return nestedBean.getPerson("TRANSACTION");
    } finally {
        if ( session.isOpen()) { // this will be true
            session.run("MATCH (a:Person) delete a");
            session.close();             // ignored, session is auto closed when the transaction ends.
        }
    }
}
 
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: 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 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: 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 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: Neo4jContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
private static void assertThatCustomPluginWasCopied(Session session) {
    StatementResult result = session.run("RETURN ac.simons.helloWorld('Testcontainers') AS greeting");
    Record singleRecord = result.single();
    assertThat(singleRecord).isNotNull();
    assertThat(singleRecord.get("greeting").asString()).isEqualTo("Hello, Testcontainers");
}