Transaction functions

You have built an application that streams the results of a long-running Cypher statement to the client.

You have written a transaction function called getCheapestFlights to execute a read query within a transaction.

View the getCheapestFlights function
Java
public static List<Record> getCheapestFlights(
    TransactionContext tx,
    String date,
    String origin,
    String destination) {

    var result = tx.run("""
        MATCH (origin:Airport)<-[:ORIGIN]-(f:Flight)-[:DESTINATION]->(destination:Airport),
            (f)-[:OPERATED_BY]->(operator:Airline)
        WHERE origin.name = $origin AND destination.name = $destination AND f.date = $date
        RETURN f.price AS price, operator.name AS operator
        """, Map.of("date", date, "origin", origin, "destination", destination));

    return result.list();
}

Read transactions

Select the correct function to execute the Cypher statement in a read transaction and stream the results to the client as soon as they are available.

Java
try (var session = driver.session()) {
    var result = session./*select:executeRead(*/
        tx -> getCheapestFlights(
            tx,
            "2024-01-01",
            "LAX",
            "SFO"
            )
        );
    var records = result.list();
}
  • ❏ cypher(

  • ✓ executeRead(

  • ❏ executeWrite(

  • ❏ execute(

Hint

When reading data from Neo4j, use executeRead() to run a read transaction. This ensures that the transaction is properly managed and allows for streaming results back to the client.

Solution

The correct answer is executeRead().

executeRead() is the recommended method for running read transactions in Neo4j. The function handles transaction management automatically and allows for streaming results as they become available.

Java
try (var session = driver.session()) {
    var result = session.executeWrite(
        tx -> getCheapestFlights(
            tx,
            "2024-01-01",
            "LAX",
            "SFO"
            )
        );
}

Summary

In this lesson, you demonstrated how to execute a read transaction using the executeRead() method. The method handles transaction management automatically and allows for streaming results as they become available.

The executeRead() method is the recommended way to run read transactions as it:

  • Automatically handles transaction management

  • Enables streaming of results as they become available

  • Ensures proper transaction lifecycle and resource cleanup

Consuming results

Remember that the results must be consumed within the transaction function. Once the transaction is completed, the results are no longer available.