org.neo4j.driver.Result Java Examples

The following examples show how to use org.neo4j.driver.Result. 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: RemoteNeo4jRepositoryImpl.java    From extended-objects with Apache License 2.0 6 votes vote down vote up
@Override
protected <T> ResultIterable<T> find(RemoteLabel label, PropertyMetadata datastoreMetadata, Object value) {
    String statement = String.format("MATCH (n:%s{%s:$value}) RETURN n", label.getName(), datastoreMetadata.getName());
    Result statementResult = statementExecutor.execute(statement, Values.parameters("value", parameterConverter.convert(value)));
    return xoSession.toResult(new ResultIterator<RemoteNode>() {

        @Override
        public boolean hasNext() {
            return statementResult.hasNext();
        }

        @Override
        public RemoteNode next() {
            Record record = statementResult.next();
            return valueConverter.convert(record.get("n").asNode());
        }

        @Override
        public void close() {
            statementResult.consume();
        }
    });
}
 
Example #2
Source File: Neo4jOperationsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveAll() {
	String thing1Name = "testThing1";
	String thing2Name = "testThing2";
	ThingWithGeneratedId thing1 = new ThingWithGeneratedId(thing1Name);
	ThingWithGeneratedId thing2 = new ThingWithGeneratedId(thing2Name);
	List<ThingWithGeneratedId> savedThings = neo4jOperations.saveAll(Arrays.asList(thing1, thing2));

	assertThat(savedThings).hasSize(2);

	try (Session session = driver.session(getSessionConfig())) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("name1", thing1Name);
		paramMap.put("name2", thing2Name);

		Result result = session.run(
			"MATCH (t:ThingWithGeneratedId) WHERE t.name = $name1 or t.name = $name2 return t",
			paramMap);
		List<Record> resultValues = result.list();
		assertThat(resultValues).hasSize(2);
		assertThat(resultValues).allMatch(record ->
			record.asMap(Function.identity()).get("t").get("name").asString().startsWith("testThing"));
	}
}
 
Example #3
Source File: Neo4JGraphWhileExecuteTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void givenTextCypherStatementShouldExecuteIt() {
    // arrange
    Mockito.when(driver.session(Mockito.any())).thenReturn(session);
    Mockito.when(session.beginTransaction()).thenAnswer(invocation -> transaction);
    Mockito.when(transaction.run(Mockito.any(String.class), Mockito.anyMap())).thenAnswer(invocation -> statementResult);
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    try (Neo4JGraph graph = new Neo4JGraph(driver, provider, provider)) {
        // act
        Result result = graph.execute("MATCH (n) RETURN n");
        // assert
        Assert.assertNotNull("Failed to execute CYPHER statement", result);
        Mockito.verify(transaction, Mockito.times(1)).run(Mockito.any(String.class), Mockito.anyMap());
    }
}
 
Example #4
Source File: Neo4JGraphWhileExecuteTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void givenCypherStatementShouldExecuteIt() {
    // arrange
    Mockito.when(driver.session(Mockito.any())).thenReturn(session);
    Mockito.when(session.beginTransaction()).thenAnswer(invocation -> transaction);
    Mockito.when(transaction.run(Mockito.any(String.class), Mockito.anyMap())).thenAnswer(invocation -> statementResult);
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    try (Neo4JGraph graph = new Neo4JGraph(driver, provider, provider)) {
        // act
        Result result = graph.execute("MATCH (n) RETURN n");
        // assert
        Assert.assertNotNull("Failed to execute CYPHER statement", result);
        Mockito.verify(transaction, Mockito.times(1)).run(Mockito.any(String.class), Mockito.anyMap());
    }
}
 
Example #5
Source File: ReactiveNeo4jOperationsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveAll() {
	String thing1Name = "testThing1";
	String thing2Name = "testThing2";
	ThingWithGeneratedId thing1 = new ThingWithGeneratedId(thing1Name);
	ThingWithGeneratedId thing2 = new ThingWithGeneratedId(thing2Name);

	StepVerifier.create(neo4jOperations.saveAll(Arrays.asList(thing1, thing2)))
		.expectNextCount(2)
		.verifyComplete();

	try (Session session = driver.session(getSessionConfig())) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("name1", thing1Name);
		paramMap.put("name2", thing2Name);

		Result result = session.run(
			"MATCH (t:ThingWithGeneratedId) WHERE t.name = $name1 or t.name = $name2 return t",
			paramMap);
		List<Record> resultValues = result.list();
		assertThat(resultValues).hasSize(2);
		assertThat(resultValues).allMatch(record ->
			record.asMap(Function.identity()).get("t").get("name").asString().startsWith("testThing"));
	}
}
 
Example #6
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
public Iterator<Edge> edges(String statement, Value parameters) {
    Objects.requireNonNull(statement, "statement cannot be null");
    Objects.requireNonNull(parameters, "parameters cannot be null");
    // get current session
    Neo4JSession session = currentSession();
    // transaction should be ready for io operations
    transaction.readWrite();
    // execute statement
    Result result = session.executeStatement(statement, parameters);
    // find edges
    Iterator<Edge> iterator = session.edges(result)
        .collect(Collectors.toCollection(LinkedList::new))
        .iterator();
    // process summary (query has been already consumed by collect)
    ResultSummaryLogger.log(result.consume());
    // return iterator
    return iterator;
}
 
Example #7
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
public Iterator<Edge> edges(String statement, Map<String, Object> parameters) {
    Objects.requireNonNull(statement, "statement cannot be null");
    Objects.requireNonNull(parameters, "parameters cannot be null");
    // get current session
    Neo4JSession session = currentSession();
    // transaction should be ready for io operations
    transaction.readWrite();
    // execute statement
    Result result = session.executeStatement(statement, parameters);
    // find edges
    Iterator<Edge> iterator = session.edges(result)
        .collect(Collectors.toCollection(LinkedList::new))
        .iterator();
    // process summary (query has been already consumed by collect)
    ResultSummaryLogger.log(result.consume());
    // return iterator
    return iterator;
}
 
Example #8
Source File: Neo4JGraphWhileExecuteTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void givenCypherStatementWithParametersShouldExecuteIt() {
    // arrange
    Mockito.when(driver.session(Mockito.any())).thenReturn(session);
    Mockito.when(session.beginTransaction()).thenAnswer(invocation -> transaction);
    Mockito.when(transaction.run(Mockito.any(String.class), Mockito.anyMap())).thenAnswer(invocation -> statementResult);
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    try (Neo4JGraph graph = new Neo4JGraph(driver, provider, provider)) {
        // act
        Result result = graph.execute("MATCH (n{id: $id}) RETURN n", Collections.singletonMap("id", 10));
        // assert
        Assert.assertNotNull("Failed to execute CYPHER statement", result);
        Mockito.verify(transaction, Mockito.times(1)).run(Mockito.any(String.class), Mockito.anyMap());
    }
}
 
Example #9
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
public Iterator<Vertex> vertices(String statement, Map<String, Object> parameters) {
    Objects.requireNonNull(statement, "statement cannot be null");
    Objects.requireNonNull(parameters, "parameters cannot be null");
    // get current session
    Neo4JSession session = currentSession();
    // transaction should be ready for io operations
    transaction.readWrite();
    // execute statement
    Result result = session.executeStatement(statement, parameters);
    // find vertices
    Iterator<Vertex> iterator = session.vertices(result)
        .collect(Collectors.toCollection(LinkedList::new))
        .iterator();
    // process summary (query has been already consumed by collect)
    ResultSummaryLogger.log(result.consume());
    // return iterator
    return iterator;
}
 
Example #10
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
public Iterator<Vertex> vertices(String statement, Value parameters) {
    Objects.requireNonNull(statement, "statement cannot be null");
    Objects.requireNonNull(parameters, "parameters cannot be null");
    // get current session
    Neo4JSession session = currentSession();
    // transaction should be ready for io operations
    transaction.readWrite();
    // execute statement
    Result result = session.executeStatement(statement, parameters);
    // find vertices
    Iterator<Vertex> iterator = session.vertices(result)
        .collect(Collectors.toCollection(LinkedList::new))
        .iterator();
    // process summary (query has been already consumed by collect)
    ResultSummaryLogger.log(result.consume());
    // return iterator
    return iterator;
}
 
Example #11
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
private void createEdges() {
    // insert edges
    for (Neo4JEdge edge : transientEdges) {
        // create command
        Neo4JDatabaseCommand command = edge.insertCommand();
        // execute statement
        Result result = executeStatement(command.getStatement(), command.getParameters());
        // process result
        command.getCallback().accept(result);
        // process summary
        ResultSummaryLogger.log(result.consume());
    }
}
 
Example #12
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
private void updateVertices() {
    // update vertices
    for (Neo4JVertex vertex : vertexUpdateQueue) {
        // create command
        Neo4JDatabaseCommand command = vertex.updateCommand();
        if (command != null) {
            // execute statement
            Result result = executeStatement(command.getStatement(), command.getParameters());
            // process result
            command.getCallback().accept(result);
            // process summary
            ResultSummaryLogger.log(result.consume());
        }
    }
}
 
Example #13
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
private void updateEdges() {
    // update edges
    for (Neo4JEdge edge : edgeUpdateQueue) {
        // create command
        Neo4JDatabaseCommand command = edge.updateCommand();
        if (command != null) {
            // execute statement
            Result result = executeStatement(command.getStatement(), command.getParameters());
            // process result
            command.getCallback().accept(result);
            // process summary
            ResultSummaryLogger.log(result.consume());
        }
    }
}
 
Example #14
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
private void deleteEdges() {
    // delete edges
    for (Neo4JEdge edge : edgeDeleteQueue) {
        // create command
        Neo4JDatabaseCommand command = edge.deleteCommand();
        // execute statement
        Result result = executeStatement(command.getStatement(), command.getParameters());
        // process result
        command.getCallback().accept(result);
        // process summary
        ResultSummaryLogger.log(result.consume());
    }
}
 
Example #15
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
Result executeStatement(String statement, Map<String, Object> parameters) {
    try {
        // statement (we are modifying text)
        String cypherStatement = statement;
        // check we need to modify statement
        if (profilerEnabled) {
            // statement text
            String text = statement;
            if (text != null) {
                // use upper case
                text = text.toUpperCase(Locale.US);
                // check we can append PROFILE to current statement
                if (!text.startsWith("PROFILE") && !text.startsWith("EXPLAIN")) {
                    // create new statement
                    cypherStatement = "PROFILE " + statement;
                }
            }
        }
        // log information
        if (logger.isDebugEnabled())
            logger.debug("Executing Cypher statement on transaction [{}]: {}", transaction.hashCode(), cypherStatement);
        // execute on transaction
        return transaction.run(cypherStatement, parameters);
    }
    catch (ClientException ex) {
        // log error
        if (logger.isErrorEnabled())
            logger.error("Error executing Cypher statement on transaction [{}]", transaction.hashCode(), ex);
        // throw original exception
        throw ex;
    }
}
 
Example #16
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
Result executeStatement(String statement, Value parameters) {
    try {
        // statement (we are modifying text)
        String cypherStatement = statement;
        // check we need to modify statement
        if (profilerEnabled) {
            // statement text
            String text = statement;
            if (text != null) {
                // use upper case
                text = text.toUpperCase(Locale.US);
                // check we can append PROFILE to current statement
                if (!text.startsWith("PROFILE") && !text.startsWith("EXPLAIN")) {
                    // create new statement
                    cypherStatement = "PROFILE " + statement;
                }
            }
        }
        // log information
        if (logger.isDebugEnabled())
            logger.debug("Executing Cypher statement on transaction [{}]: {}", transaction.hashCode(), cypherStatement);
        // execute on transaction
        return transaction.run(cypherStatement, parameters);
    }
    catch (ClientException ex) {
        // log error
        if (logger.isErrorEnabled())
            logger.error("Error executing Cypher statement on transaction [{}]", transaction.hashCode(), ex);
        // throw original exception
        throw ex;
    }
}
 
Example #17
Source File: CypherTransactionWork.java    From knowbi-pentaho-pdi-neo4j-output with Apache License 2.0 5 votes vote down vote up
@Override public Void execute( Transaction tx ) {
  Result result = tx.run( cypher, unwindMap );
  try {
    step.getResultRows( result, currentRow, unwind );
    return null;
  } catch ( KettleException e ) {
    throw new RuntimeException( "Unable to execute cypher statement '"+cypher+"'", e );
  }
}
 
Example #18
Source File: Cypher.java    From knowbi-pentaho-pdi-neo4j-output with Apache License 2.0 5 votes vote down vote up
private boolean processSummary( Result result ) {
  boolean error = false;
  ResultSummary summary = result.consume();
  for ( Notification notification : summary.notifications() ) {
    log.logError( notification.title() + " (" + notification.severity() + ")" );
    log.logError( notification.code() + " : " + notification.description() + ", position " + notification.position() );
    error = true;
  }
  return error;
}
 
Example #19
Source File: Neo4JOutput.java    From knowbi-pentaho-pdi-neo4j-output with Apache License 2.0 5 votes vote down vote up
private void processSummary( Result result ) throws KettleException {
  boolean error = false;
  ResultSummary summary = result.consume();
  for ( Notification notification : summary.notifications() ) {
    log.logError( notification.title() + " (" + notification.severity() + ")" );
    log.logError( notification.code() + " : " + notification.description() + ", position " + notification.position() );
    error = true;
  }
  if ( error ) {
    throw new KettleException( "Error found while executing cypher statement(s)" );
  }
}
 
Example #20
Source File: GraphOutput.java    From knowbi-pentaho-pdi-neo4j-output with Apache License 2.0 5 votes vote down vote up
private boolean executeStatement( GraphOutputData data, String cypher, Map<String, Object> parameters ) {
  Result result;
  boolean errors = false;
  if ( data.batchSize <= 1 ) {
    result = data.session.run( cypher, parameters );
    errors = processSummary( result );
  } else {
    if ( data.outputCount == 0 ) {
      data.transaction = data.session.beginTransaction();
    }
    result = data.transaction.run( cypher, parameters );
    errors = processSummary( result );

    data.outputCount++;
    incrementLinesOutput();

    if ( !errors && data.outputCount >= data.batchSize ) {
      data.transaction.commit();
      data.transaction.close();
      data.outputCount = 0;
    }
  }

  if ( errors ) {
    setErrors( 1L );
    stopAll();
    setOutputDone();
  }

  if ( log.isDebug() ) {
    logDebug( "Result : " + result.toString() );
  }
  return errors;
}
 
Example #21
Source File: GraphOutput.java    From knowbi-pentaho-pdi-neo4j-output with Apache License 2.0 5 votes vote down vote up
private boolean processSummary( Result result ) {
  boolean errors = false;
  ResultSummary summary = result.consume();
  for ( Notification notification : summary.notifications() ) {
    log.logError( notification.title() + " (" + notification.severity() + ")" );
    log.logError( notification.code() + " : " + notification.description() + ", position " + notification.position() );
    errors = true;
  }
  return errors;
}
 
Example #22
Source File: RemoteDatastoreRelationManager.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
private StateTracker<RemoteRelationship, Set<RemoteRelationship>> getRelationships(RemoteNode source, RemoteRelationshipType type,
        RemoteDirection remoteDirection) {
    StateTracker<RemoteRelationship, Set<RemoteRelationship>> trackedRelationships = source.getState().getRelationships(remoteDirection, type);
    if (trackedRelationships == null) {
        String sourceIdentifier;
        switch (remoteDirection) {
        case OUTGOING:
            sourceIdentifier = "start";
            break;
        case INCOMING:
            sourceIdentifier = "end";
            break;
        default:
            throw new XOException("Direction not supported: " + remoteDirection);
        }
        String statement = String.format("MATCH (start)-[r:%s]->(end) WHERE id(%s)=$id RETURN start,r,end", type.getName(), sourceIdentifier);
        Result statementResult = statementExecutor.execute(statement, parameters("id", source.getId()));
        Set<RemoteRelationship> loaded = new LinkedHashSet<>();
        try {
            while (statementResult.hasNext()) {
                Record record = statementResult.next();
                Node start = record.get("start").asNode();
                Relationship relationship = record.get("r").asRelationship();
                Node end = record.get("end").asNode();
                RemoteRelationship remoteRelationship = datastoreSessionCache.getRelationship(start, relationship, end);
                loaded.add(remoteRelationship);
            }
        } finally {
            statementResult.consume();
        }
        trackedRelationships = new StateTracker<>(loaded);
        source.getState().setRelationships(remoteDirection, type, trackedRelationships);
    }
    return trackedRelationships;
}
 
Example #23
Source File: StatementExecutor.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
public Result execute(String statement, Map<String, Object> parameters) {
    LogLevel statementLogger = statementConfig.getLogLevel();
    if (!LogLevel.NONE.equals(statementLogger)) {
        statementLogger.log(LOGGER, "'" + statement + "': " + parameters);
    }
    try {
        QueryRunner queryRunner = transaction.getQueryRunner();
        return queryRunner.run(statement, parameters);
    } catch (Neo4jException e) {
        throw new XOException("Cannot execute statement '" + statement + "', " + parameters, e);
    }
}
 
Example #24
Source File: StatementExecutor.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
private Record getSingleResult(Result result) {
    try {
        return result.single();
    } catch (NoSuchRecordException e) {
        throw new XOException("Query returned no result.");
    } finally {
        result.consume();
    }
}
 
Example #25
Source File: RemoteDatastoreEntityManager.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
@Override
public ResultIterator<RemoteNode> findEntity(EntityTypeMetadata<NodeMetadata<RemoteLabel>> type, RemoteLabel remoteLabel,
        Map<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> values) {
    if (values.size() > 1) {
        throw new XOException("Only one property value is supported for find operation");
    }
    Map.Entry<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> entry = values.entrySet().iterator().next();
    PropertyMetadata propertyMetadata = getIndexedPropertyMetadata(type, entry.getKey());
    Object value = entry.getValue();
    String statement = String.format("MATCH (n:%s) WHERE n.%s=$v RETURN n", remoteLabel.getName(), propertyMetadata.getName());
    Result result = statementExecutor.execute(statement, parameters("v", value));
    return new ResultIterator<RemoteNode>() {
        @Override
        public boolean hasNext() {
            return result.hasNext();
        }

        @Override
        public RemoteNode next() {
            Record record = result.next();
            Node node = record.get("n").asNode();
            return datastoreSessionCache.getNode(node);
        }

        @Override
        public void close() {
            result.consume();
        }
    };
}
 
Example #26
Source File: ReactiveNeo4jOperationsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void deleteAllById() {
	StepVerifier
		.create(neo4jOperations.deleteAllById(Arrays.asList(person1Id, person2Id), PersonWithAllConstructor.class))
		.verifyComplete();

	try (Session session = driver.session(getSessionConfig())) {
		Result result = session.run("MATCH (p:PersonWithAllConstructor) return count(p) as count");
		assertThat(result.single().get("count").asLong()).isEqualTo(0);
	}
}
 
Example #27
Source File: DefaultNeo4jClient.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public ResultSummary run() {

	try (AutoCloseableQueryRunner statementRunner = getQueryRunner(this.targetDatabase)) {
		Result result = runnableStatement.runWith(statementRunner);
		return result.consume();
	} catch (RuntimeException e) {
		throw potentiallyConvertRuntimeException(e, persistenceExceptionTranslator);
	}
}
 
Example #28
Source File: DefaultNeo4jClient.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<T> one() {

	try (AutoCloseableQueryRunner statementRunner = getQueryRunner(this.targetDatabase)) {
		Result result = runnableStatement.runWith(statementRunner);
		return result.hasNext() ?
			Optional.of(mappingFunction.apply(typeSystem, result.single())) :
			Optional.empty();
	} catch (RuntimeException e) {
		throw potentiallyConvertRuntimeException(e, persistenceExceptionTranslator);
	}
}
 
Example #29
Source File: DefaultNeo4jClient.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<T> first() {

	try (AutoCloseableQueryRunner statementRunner = getQueryRunner(this.targetDatabase)) {
		Result result = runnableStatement.runWith(statementRunner);
		return result.stream().map(partialMappingFunction(typeSystem)).findFirst();
	} catch (RuntimeException e) {
		throw potentiallyConvertRuntimeException(e, persistenceExceptionTranslator);
	}
}
 
Example #30
Source File: DefaultNeo4jClient.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<T> all() {

	try (AutoCloseableQueryRunner statementRunner = getQueryRunner(this.targetDatabase)) {
		Result result = runnableStatement.runWith(statementRunner);
		return result.stream().map(partialMappingFunction(typeSystem)).collect(toList());
	} catch (RuntimeException e) {
		throw potentiallyConvertRuntimeException(e, persistenceExceptionTranslator);
	}
}