org.neo4j.driver.summary.ResultSummary Java Examples

The following examples show how to use org.neo4j.driver.summary.ResultSummary. 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: Neo4jTemplate.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void deleteById(Object id, Class<T> domainType) {

	Neo4jPersistentEntity entityMetaData = neo4jMappingContext.getPersistentEntity(domainType);
	String nameOfParameter = "id";
	Condition condition = entityMetaData.getIdExpression().isEqualTo(parameter(nameOfParameter));

	log.debug(() -> String.format("Deleting entity with id %s ", id));

	Statement statement = cypherGenerator.prepareDeleteOf(entityMetaData, condition);
	ResultSummary summary = this.neo4jClient.query(renderer.render(statement))
		.in(getDatabaseName())
		.bind(id).to(nameOfParameter)
		.run();

	log.debug(() -> String.format("Deleted %d nodes and %d relationships.", summary.counters().nodesDeleted(),
		summary.counters().relationshipsDeleted()));
}
 
Example #2
Source File: Neo4jTemplate.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void deleteAllById(Iterable<?> ids, Class<T> domainType) {

	Neo4jPersistentEntity entityMetaData = neo4jMappingContext.getPersistentEntity(domainType);
	String nameOfParameter = "ids";
	Condition condition = entityMetaData.getIdExpression().in(parameter(nameOfParameter));

	log.debug(() -> String.format("Deleting all entities with the following ids: %s ", ids));

	Statement statement = cypherGenerator.prepareDeleteOf(entityMetaData, condition);
	ResultSummary summary = this.neo4jClient.query(renderer.render(statement))
		.in(getDatabaseName())
		.bind(ids).to(nameOfParameter)
		.run();

	log.debug(() -> String.format("Deleted %d nodes and %d relationships.", summary.counters().nodesDeleted(),
		summary.counters().relationshipsDeleted()));
}
 
Example #3
Source File: Neo4jHealthCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {

    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Neo4j connection health check").up();
    try {
        ResultSummary resultSummary;
        // Retry one time when the session has been expired
        try {
            resultSummary = runHealthCheckQuery();
        } catch (SessionExpiredException sessionExpiredException) {
            log.warn(MESSAGE_SESSION_EXPIRED);
            resultSummary = runHealthCheckQuery();
        }
        return buildStatusUp(resultSummary, builder);
    } catch (Exception e) {
        return builder.down().withData("reason", e.getMessage()).build();
    }
}
 
Example #4
Source File: DefaultReactiveNeo4jClient.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ResultSummary> run() {

	return new DefaultRecordFetchSpec<>(
		this.targetDatabase,
		this.cypherSupplier,
		this.parameters).run();
}
 
Example #5
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 #6
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 #7
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 #8
Source File: ResultSummaryLogger.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
public static void log(ResultSummary summary) {
    Objects.requireNonNull(summary, "summary cannot be null");
    // log information
    if (logger.isInfoEnabled() && summary.hasProfile()) {
        // create builder
        StringBuilder builder = new StringBuilder();
        // append statement
        builder.append("Profile for CYPHER statement: ").append(summary.query().text()).append("\n");
        // create profile information
        ProfileInformation profileInformation = new ProfileInformation();
        // process profile
        profileInformation.process(summary.profile());
        // log tabular results
        builder.append(profileInformation.toString());
        // log information
        logger.info(builder.toString());
    }
    // log notifications
    if (logger.isWarnEnabled()) {
        // loop notifications
        for (Notification notification : summary.notifications()) {
            // position if any
            InputPosition position = notification.position();
            // log information
            logger.warn("CYPHER statement [{}] notification; severity: {}, code: {}, title: {}, description: {}{}", summary.query().text(), notification.severity(), notification.code(), notification.title(), notification.description(), position != null ? ", [line: " + position.line() + ", position: " + position.column() + ", offset: " + position.offset() + "]" : "");
        }
    }
}
 
Example #9
Source File: Neo4jHealthCheck.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private ResultSummary runHealthCheckQuery() {
    // We use WRITE here to make sure UP is returned for a server that supports
    // all possible workloads
    try (Session session = this.driver.session(DEFAULT_SESSION_CONFIG)) {
        ResultSummary resultSummary = session.run(CYPHER).consume();
        return resultSummary;
    }
}
 
Example #10
Source File: Neo4jHealthCheck.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given {@link ResultSummary} to the {@link HealthCheckResponseBuilder builder} and calls {@code build}
 * afterwards.
 *
 * @param resultSummary the result summary returned by the server
 * @param builder the health builder to be modified
 * @return the final {@link HealthCheckResponse health check response}
 */
private static HealthCheckResponse buildStatusUp(ResultSummary resultSummary, HealthCheckResponseBuilder builder) {
    ServerInfo serverInfo = resultSummary.server();

    builder.withData("server", serverInfo.version() + "@" + serverInfo.address());

    String databaseName = resultSummary.database().name();
    if (!(databaseName == null || databaseName.trim().isEmpty())) {
        builder.withData("database", databaseName.trim());
    }

    return builder.build();
}
 
Example #11
Source File: ReactiveNeo4jClientTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Queries that return nothing should fit in")
void queriesWithoutResultShouldFitInAsWell() {

	prepareMocks();

	when(transaction.run(anyString(), anyMap())).thenReturn(result);
	when(transaction.commit()).thenReturn(Mono.empty());
	when(result.records()).thenReturn(Flux.empty());
	when(result.consume()).thenReturn(Mono.just(resultSummary));

	ReactiveNeo4jClient client = ReactiveNeo4jClient.create(driver);

	String cypher = "DETACH DELETE (b) WHERE name = $name";

	Mono<ResultSummary> deletionResult = client
		.query(cypher)
		.bind("fixie").to("name")
		.run();

	StepVerifier.create(deletionResult)
		.expectNext(resultSummary)
		.verifyComplete();

	verifyDatabaseSelection(null);

	Map<String, Object> expectedParameters = new HashMap<>();
	expectedParameters.put("name", "fixie");

	verify(transaction).run(eq(cypher), argThat(new MapAssertionMatcher(expectedParameters)));
	verify(result).consume();
	verify(transaction).commit();
	verify(transaction).rollback();
	verify(session).close();
}
 
Example #12
Source File: ReactiveNeo4jClientTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void writing() {

	prepareMocks();

	when(transaction.run(anyString(), anyMap())).thenReturn(result);
	when(transaction.commit()).thenReturn(Mono.empty());
	when(result.records()).thenReturn(Flux.empty());
	when(result.consume()).thenReturn(Mono.just(resultSummary));

	ReactiveNeo4jClient client = ReactiveNeo4jClient.create(driver);

	BikeOwner michael = new BikeOwner("Michael", Arrays.asList(new Bike("Road"), new Bike("MTB")));
	String cypher = "MERGE (u:User {name: 'Michael'}) "
		+ "WITH u UNWIND $bikes as bike "
		+ "MERGE (b:Bike {name: bike}) "
		+ "MERGE (u) - [o:OWNS] -> (b) ";

	Mono<ResultSummary> summary = client
		.query(cypher)
		.bind(michael).with(new BikeOwnerBinder())
		.run();

	StepVerifier.create(summary)
		.expectNext(resultSummary)
		.verifyComplete();

	verifyDatabaseSelection(null);

	Map<String, Object> expectedParameters = new HashMap<>();
	expectedParameters.put("name", "Michael");

	verify(transaction).run(eq(cypher), argThat(new MapAssertionMatcher(expectedParameters)));
	verify(result).consume();
	verify(transaction).commit();
	verify(transaction).rollback();
	verify(session).close();
}
 
Example #13
Source File: Neo4jClientTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void writing() {

	prepareMocks();

	when(session.run(anyString(), anyMap())).thenReturn(result);
	when(result.consume()).thenReturn(resultSummary);

	Neo4jClient client = Neo4jClient.create(driver);

	BikeOwner michael = new BikeOwner("Michael", Arrays.asList(new Bike("Road"), new Bike("MTB")));
	String cypher = "MERGE (u:User {name: 'Michael'}) "
		+ "WITH u UNWIND $bikes as bike "
		+ "MERGE (b:Bike {name: bike}) "
		+ "MERGE (u) - [o:OWNS] -> (b) ";
	ResultSummary summary = client
		.query(cypher)
		.bind(michael).with(new BikeOwnerBinder())
		.run();

	verifyDatabaseSelection(null);

	Map<String, Object> expectedParameters = new HashMap<>();
	expectedParameters.put("name", "Michael");

	verify(session).run(eq(cypher), argThat(new MapAssertionMatcher(expectedParameters)));
	verify(result).consume();
	verify(session).close();
}
 
Example #14
Source File: ExceptionTranslationIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void exceptionsOnRepositoryBeansShouldBeTranslated(@Autowired CustomDAO customDAO) {
	ResultSummary summary = customDAO.createPerson();
	assertThat(summary.counters().nodesCreated()).isEqualTo(1L);

	assertThatExceptionOfType(DataIntegrityViolationException.class)
		.isThrownBy(() -> customDAO.createPerson())
		.withMessageMatching(
			"Node\\(\\d+\\) already exists with label `SimplePerson` and property `name` = '[\\w\\s]+'; Error code 'Neo.ClientError.Schema.ConstraintValidationFailed'");
}
 
Example #15
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 #16
Source File: Neo4jTemplate.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteAll(Class<?> domainType) {

	Neo4jPersistentEntity entityMetaData = neo4jMappingContext.getPersistentEntity(domainType);
	log.debug(() -> String.format("Deleting all nodes with primary label %s", entityMetaData.getPrimaryLabel()));

	Statement statement = cypherGenerator.prepareDeleteOf(entityMetaData);
	ResultSummary summary = this.neo4jClient.query(renderer.render(statement)).in(getDatabaseName()).run();

	log.debug(() -> String.format("Deleted %d nodes and %d relationships.", summary.counters().nodesDeleted(),
		summary.counters().relationshipsDeleted()));
}
 
Example #17
Source File: DefaultReactiveNeo4jClient.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
Mono<ResultSummary> run() {

			return doInQueryRunnerForMono(
				targetDatabase,
				runner -> prepareStatement().flatMap(t -> {
					RxResult rxResult = runner.run(t.getT1(), t.getT2());
					return Flux.from(rxResult.records()).then(Mono.from(rxResult.consume()));
				})
			).onErrorMap(RuntimeException.class, DefaultReactiveNeo4jClient.this::potentiallyConvertRuntimeException);
		}
 
Example #18
Source File: DataNeo4jTestIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void driverShouldBeConnectedToNeo4jTestHarness(@Autowired ServerControls serverControls,
	@Autowired Neo4jClient client) {

	ResultSummary summary = client.query("RETURN 1 AS result").run();
	URI uri = serverControls.boltURI();
	assertThat(summary.server().address()).endsWith(String.format("%s:%d", uri.getHost(), uri.getPort()));
}
 
Example #19
Source File: ReactiveExceptionTranslationIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
public Mono<ResultSummary> createPerson() {
	return neo4jClient.delegateTo(rxQueryRunner -> {
		RxResult rxResult = rxQueryRunner.run("CREATE (:SimplePerson {name: 'Tom'})");
		return Flux.from(rxResult.records()).then(Mono.from(rxResult.consume()));
	}).run();
}
 
Example #20
Source File: ExceptionTranslationIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
public ResultSummary createPerson() {

			return neo4jClient.delegateTo(queryRunner ->
				Optional.of(queryRunner.run("CREATE (:SimplePerson {name: 'Tom'})").consume()))
				.run().get();
		}
 
Example #21
Source File: Neo4jTemplate.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Override
public <T> List<T> saveAll(Iterable<T> instances) {

	String databaseName = getDatabaseName();

	Collection<T> entities;
	if (instances instanceof Collection) {
		entities = (Collection<T>) instances;
	} else {
		entities = new ArrayList<>();
		instances.forEach(entities::add);
	}

	if (entities.isEmpty()) {
		return Collections.emptyList();
	}

	Class<T> domainClass = (Class<T>) CollectionUtils.findCommonElementType(entities);
	Neo4jPersistentEntity entityMetaData = neo4jMappingContext.getPersistentEntity(domainClass);
	if (entityMetaData.isUsingInternalIds() || entityMetaData.hasVersionProperty()) {
		log.debug("Saving entities using single statements.");

		return entities.stream()
			.map(e -> saveImpl(e, databaseName))
			.collect(toList());
	}

	List<T> entitiesToBeSaved = entities.stream()
		.map(eventSupport::maybeCallBeforeBind)
		.collect(toList());

	// Save roots
	Function<T, Map<String, Object>> binderFunction = neo4jMappingContext.getRequiredBinderFunctionFor(domainClass);
	List<Map<String, Object>> entityList = entitiesToBeSaved.stream()
		.map(binderFunction).collect(toList());
	ResultSummary resultSummary = neo4jClient
		.query(() -> renderer.render(cypherGenerator.prepareSaveOfMultipleInstancesOf(entityMetaData)))
		.in(databaseName)
		.bind(entityList).to(NAME_OF_ENTITY_LIST_PARAM)
		.run();

	// Save related
	entitiesToBeSaved.forEach(entityToBeSaved -> processRelations(entityMetaData, entityToBeSaved, databaseName));

	SummaryCounters counters = resultSummary.counters();
	log.debug(() -> String
		.format("Created %d and deleted %d nodes, created %d and deleted %d relationships and set %d properties.",
			counters.nodesCreated(), counters.nodesDeleted(), counters.relationshipsCreated(),
			counters.relationshipsDeleted(), counters.propertiesSet()));

	return entitiesToBeSaved;
}
 
Example #22
Source File: Neo4jBoltBuffer.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
public void addResultSummary(ResultSummary resultSummary) {
    this.resultSummary = resultSummary;
}
 
Example #23
Source File: Neo4jBoltBuffer.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
public ResultSummary getResultSummary() {
    return resultSummary;
}
 
Example #24
Source File: Neo4jBoltBuffer.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
public boolean hasPlan() {
    return Optional.ofNullable(resultSummary)
            .map(ResultSummary::hasPlan)
            .orElse(false);
}
 
Example #25
Source File: Neo4jBoltBuffer.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
public boolean isProfilePlan() {
    return Optional.ofNullable(resultSummary)
            .map(ResultSummary::hasProfile)
            .orElse(false);
}
 
Example #26
Source File: Neo4jBoltQueryResult.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
@Override
public String getResultSummary() {
    ResultSummary summary = buffer.getResultSummary();
    SummaryCounters counters = summary.counters();

    StringBuilder sb = new StringBuilder();
    sb.append(format("Query type: %s.\n", summary.queryType()));
    if (counters.containsUpdates()) {
        if (counters.nodesCreated() > 0) {
            sb.append(format("Nodes created: %s\n", counters.nodesCreated()));
        }
        if (counters.nodesDeleted() > 0) {
            sb.append(format("Nodes deleted: %s\n", counters.nodesDeleted()));
        }
        if (counters.labelsAdded() > 0) {
            sb.append(format("Labels added: %s\n", counters.labelsAdded()));
        }
        if (counters.labelsRemoved() > 0) {
            sb.append(format("Labels removed: %s\n", counters.labelsRemoved()));
        }
        if (counters.relationshipsCreated() > 0) {
            sb.append(format("Relationships created: %s\n", counters.relationshipsCreated()));
        }
        if (counters.relationshipsDeleted() > 0) {
            sb.append(format("Relationships deleted: %s\n", counters.relationshipsDeleted()));
        }
        if (counters.propertiesSet() > 0) {
            sb.append(format("Properties set: %s\n", counters.propertiesSet()));
        }
        if (counters.indexesAdded() > 0) {
            sb.append(format("Indexes added: %s\n", counters.indexesAdded()));
        }
        if (counters.indexesRemoved() > 0) {
            sb.append(format("Indexes removed: %s\n", counters.indexesRemoved()));
        }
        if (counters.constraintsAdded() > 0) {
            sb.append(format("Constrains added: %s\n", counters.constraintsAdded()));
        }
        if (counters.constraintsRemoved() > 0) {
            sb.append(format("Constrains removed: %s\n", counters.constraintsRemoved()));
        }
    }

    if (summary.hasProfile()) {
        sb.append("Profile:\n");
        profileToString(sb, summary.profile(), 1);
    } else if (summary.hasPlan()) {
        sb.append("Plan:\n");
        planToString(sb, summary.plan(), 1);
    }

    if (summary.notifications().size() > 0) {
        sb.append("Notifications:\n");
        for (Notification notification : summary.notifications()) {
            sb.append(format("[%s] %s(%s) - %s", notification.severity(),
                    notification.title(), notification.code(), notification.description()));
        }
    }
    return sb.toString();
}
 
Example #27
Source File: Neo4jClient.java    From sdn-rx with Apache License 2.0 2 votes vote down vote up
/**
 * Execute the query and discard the results. It returns the drivers result summary, including various counters
 * and other statistics.
 *
 * @return The native summary of the query.
 */
ResultSummary run();
 
Example #28
Source File: ReactiveNeo4jClient.java    From sdn-rx with Apache License 2.0 2 votes vote down vote up
/**
 * Execute the query and discard the results. It returns the drivers result summary, including various counters
 * and other statistics.
 *
 * @return A mono containing the native summary of the query.
 */
Mono<ResultSummary> run();