org.neo4j.driver.v1.Session Java Examples
The following examples show how to use
org.neo4j.driver.v1.Session.
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 |
@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: StatefulTestBean.java From thorntail with Apache License 2.0 | 6 votes |
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 #3
Source File: Neo4jConnectionManager.java From zeppelin with Apache License 2.0 | 6 votes |
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 #4
Source File: Neo4jContainerJUnitIntegrationTest.java From testcontainers-java with MIT License | 6 votes |
@Test public void shouldStart() { boolean actual = neo4jContainer.isRunning(); assertThat(actual).isTrue(); try (Driver driver = GraphDatabase .driver(neo4jContainer.getBoltUrl(), AuthTokens.basic("neo4j", "password")); Session session = driver.session() ) { long one = session.run("RETURN 1", Collections.emptyMap()).next().get(0).asLong(); assertThat(one).isEqualTo(1L); } catch (Exception e) { fail(e.getMessage()); } }
Example #5
Source File: Neo4jContainerTest.java From testcontainers-java with MIT License | 6 votes |
@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 #6
Source File: ExpandFlossNodes.java From SnowGraph with Apache License 2.0 | 6 votes |
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 #7
Source File: ExpandDocxNodes.java From SnowGraph with Apache License 2.0 | 6 votes |
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 #8
Source File: Neo4jContainerTest.java From testcontainers-java with MIT License | 6 votes |
@Test public void shouldRunEnterprise() { assumeThat(Neo4jContainerTest.class.getResource(ACCEPTANCE_FILE_LOCATION)).isNotNull(); try ( Neo4jContainer neo4jContainer = new Neo4jContainer() .withEnterpriseEdition() .withAdminPassword("Picard123") ) { neo4jContainer.start(); try ( Driver driver = getDriver(neo4jContainer); Session session = driver.session() ) { String edition = session .run("CALL dbms.components() YIELD edition RETURN edition", Collections.emptyMap()) .next().get(0).asString(); assertThat(edition).isEqualTo("enterprise"); } } }
Example #9
Source File: Neo4jBoltPersistWriter.java From streams with Apache License 2.0 | 6 votes |
@Override public void write(StreamsDatum entry) { List<Pair<String, Map<String, Object>>> statements; Session session = null; try { statements = Neo4jPersistUtil.prepareStatements(entry); session = client.client().session(); Transaction transaction = session.beginTransaction(); for( Pair<String, Map<String, Object>> statement : statements ) { StatementResult statementResult = transaction.run( statement.getValue0(), statement.getValue1() ); LOGGER.debug("StatementResult", statementResult.single()); } transaction.success(); } catch( Exception ex ) { LOGGER.error("Exception", ex); } finally { if( session != null ) { session.close(); } } }
Example #10
Source File: InsightsGraphDBHandler.java From Insights with Apache License 2.0 | 6 votes |
@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: InsightsGraphDBHandler.java From Insights with Apache License 2.0 | 6 votes |
@Override public void writeBulk(final List<String> queries) throws DataDeleteException { validateDeleteDetach(queries); try ( Session session = GraphDBConnection.getInstance().getDriver().session() ) { session.writeTransaction( new TransactionWork<Integer>() { @Override public Integer execute( Transaction tx ) { return createBulkNodes( tx, queries ); } } ); } }
Example #12
Source File: InsightsGraphDBHandler.java From Insights with Apache License 2.0 | 6 votes |
@Override public void write(final String query) throws DataDeleteException { deleteDetachKeywordValidation(query); try ( Session session = GraphDBConnection.getInstance().getDriver().session() ) { session.writeTransaction( new TransactionWork<Integer>() { @Override public Integer execute( Transaction tx ) { return createNode( tx, query ); } } ); } }
Example #13
Source File: QueryRunner.java From neoprofiler with Apache License 2.0 | 6 votes |
public List<NeoProperty> getSampleProperties(NeoProfiler parent, Entity n) { List<NeoProperty> props = new ArrayList<NeoProperty>(); Session s = parent.getDriver().session(); try ( Transaction tx = s.beginTransaction() ) { Iterator<String> propKeys = n.keys().iterator(); while(propKeys.hasNext()) { String key = propKeys.next(); Object val = n.get(key); props.add(new NeoProperty(key, val.getClass().getSimpleName())); } } finally { s.close(); } return props; }
Example #14
Source File: OpenCypherClientService.java From nifi with Apache License 2.0 | 6 votes |
@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 #15
Source File: Neo4jDataManager.java From rdf2neo with GNU Lesser General Public License v3.0 | 6 votes |
/** * <p>Runs a Neo4j client session, which is created and given to the action as a parameter. The action can return * a value useful for the invoker of this method.</p> * * <p>Because parallelism sometimes raises exceptions about race conditions, we use {@link MultipleAttemptsExecutor} * to re-attempt the command execution a couple of times, after such exceptions.</p> * */ @SuppressWarnings ( "unchecked" ) public <V> V runSession ( Function<Session, V> action ) { MultipleAttemptsExecutor attempter = new MultipleAttemptsExecutor ( TransientException.class, DatabaseException.class, ServiceUnavailableException.class ); attempter.setMaxAttempts ( this.getMaxRetries () ); attempter.setMinPauseTime ( 30 * 1000 ); attempter.setMaxPauseTime ( 3 * 60 * 1000 ); Object[] result = new Object [ 1 ]; attempter.execute ( () -> { try ( Session session = this.neo4jDriver.session () ) { result [ 0 ] = action.apply ( session ); } }); return (V) result [ 0 ]; }
Example #16
Source File: QueryRunner.java From neoprofiler with Apache License 2.0 | 6 votes |
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 #17
Source File: CypherHandlersIT.java From rdf2neo with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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 #18
Source File: QueryRunner.java From neoprofiler with Apache License 2.0 | 6 votes |
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 #19
Source File: StatefulTestBean.java From thorntail with Apache License 2.0 | 5 votes |
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 #20
Source File: Neo4JCypherClientService.java From nifi with Apache License 2.0 | 5 votes |
@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 #21
Source File: Neo4jContainerTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void shouldDisableAuthentication() { try ( Neo4jContainer neo4jContainer = new Neo4jContainer().withoutAuthentication(); ) { neo4jContainer.start(); try (Driver driver = getDriver(neo4jContainer); Session session = driver.session() ) { long one = session.run("RETURN 1", Collections.emptyMap()).next().get(0).asLong(); assertThat(one).isEqualTo(1L); } } }
Example #22
Source File: Neo4jContainerTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void shouldCopyPlugins() { try ( Neo4jContainer neo4jContainer = new Neo4jContainer() .withPlugins(MountableFile.forClasspathResource("/custom-plugins")); ) { neo4jContainer.start(); try ( Driver driver = getDriver(neo4jContainer); Session session = driver.session() ) { assertThatCustomPluginWasCopied(session); } } }
Example #23
Source File: QueryRunner.java From neoprofiler with Apache License 2.0 | 5 votes |
public List<Object> runQueryMultipleResult(NeoProfiler parent, String query, String columnReturn) { Session s = parent.getDriver().session(); List<Object> retvals = new ArrayList<Object>(); try ( Transaction tx = s.beginTransaction()) { // log.info(query); StatementResult result = tx.run(query); while(result.hasNext()) { retvals.add(result.next().get(columnReturn)); } } return retvals; }
Example #24
Source File: Neo4jContainerTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void shouldCopyPlugin() { try ( Neo4jContainer neo4jContainer = new Neo4jContainer() .withPlugins(MountableFile.forClasspathResource("/custom-plugins/hello-world.jar")); ) { neo4jContainer.start(); try ( Driver driver = getDriver(neo4jContainer); Session session = driver.session() ) { assertThatCustomPluginWasCopied(session); } } }
Example #25
Source File: Neo4jBoltPersistReader.java From streams with Apache License 2.0 | 5 votes |
@Override public StreamsResultSet readAll() { Session session = null; String query = config.getQuery(); Map<String, Object> params = mapper.convertValue(config.getParams(), Map.class); try { session = client.client().session(); Transaction transaction = session.beginTransaction(); this.statementResult = client.client().session().beginTransaction().run(query, params); while( statementResult.hasNext()) { Record record = statementResult.next(); Optional<StreamsDatum> datum = buildDatum(record); if( datum.isPresent()) { write(datum.get()); } } } catch(Exception ex) { LOGGER.warn("Exception", ex); } finally { if( session != null ) { session.close(); } } return readCurrent(); }
Example #26
Source File: Neo4jBoltPersistIT.java From streams with Apache License 2.0 | 5 votes |
@BeforeClass public void prepareTest() throws IOException { testConfiguration = new ComponentConfigurator<>(Neo4jConfiguration.class).detectConfiguration( "Neo4jBoltPersistIT"); testClient = Neo4jBoltClient.getInstance(testConfiguration); Session session = testClient.client().session(); Transaction transaction = session.beginTransaction(); transaction.run("MATCH ()-[r]-() DELETE r"); transaction.run("MATCH (n) DETACH DELETE n"); transaction.success(); session.close(); }
Example #27
Source File: Neo4jBoltPersistIT.java From streams with Apache License 2.0 | 5 votes |
@AfterClass public void cleanup() throws Exception { Session session = testClient.client().session(); Transaction transaction = session.beginTransaction(); transaction.run("MATCH ()-[r]-() DELETE r"); transaction.run("MATCH (n) DETACH DELETE n"); transaction.success(); session.close(); }
Example #28
Source File: TwitterFollowNeo4jIT.java From streams with Apache License 2.0 | 5 votes |
@BeforeClass public void prepareTest() throws IOException { testConfiguration = new StreamsConfigurator<>(TwitterFollowNeo4jConfiguration.class).detectCustomConfiguration(); testClient = Neo4jBoltClient.getInstance(testConfiguration.getNeo4j()); Session session = testClient.client().session(); Transaction transaction = session.beginTransaction(); transaction.run("MATCH ()-[r]-() DELETE r"); transaction.run("MATCH (n) DETACH DELETE n"); transaction.success(); session.close(); }
Example #29
Source File: TwitterFollowNeo4jIT.java From streams with Apache License 2.0 | 5 votes |
@AfterClass public void cleanup() throws Exception { Session session = testClient.client().session(); Transaction transaction = session.beginTransaction(); transaction.run("MATCH ()-[r]-() DELETE r"); transaction.run("MATCH (n) DETACH DELETE n"); transaction.success(); session.close(); }
Example #30
Source File: DatabaseConnector.java From Getaviz with Apache License 2.0 | 5 votes |
public Node addNode(String statement, String parameterName) { Node result; try (Session session = driver.session()) { try (Transaction tx = session.beginTransaction()) { result = tx.run(statement + " RETURN " + parameterName).next().get(parameterName).asNode(); tx.success(); // Mark this write as successful. } } return result; }