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 get_cheapest_flights
to execute a read query within a transaction.
View the get_cheapest_flights
function
def get_cheapest_flights(tx, date, origin, destination):
"""
Return the cheapest flights between the origin and
destination airports on a given date.
"""
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
""", date=date, origin=origin, destination=destination)
return result.values()
The application then uses an external function called send_to_ui
to send the results to the client.
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.
from api import send_to_ui
with driver.session() as session:
res = session.#select:execute_read(
get_cheapest_flights,
date="2024-01-01",
origin="LAX",
destination="SFO"
)
for row in res:
send_to_ui(row)
-
❏ cypher(
-
✓ execute_read(
-
❏ execute_write(
-
❏ run_async(
Hint
When reading data from Neo4j, use execute_read()
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 execute_read()
.
execute_read()
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.
with driver.session() as session:
res = session.execute_read(
get_cheapest_flights,
date="2024-01-01",
origin="LAX",
destination="SFO"
)
for row in res:
send_to_ui(row)
The other options are incorrect because:
-
run()
is deprecated and should not be used -
execute_write()
is for write transactions only -
run_async()
is not a valid method for the session object
Summary
In this lesson, you demonstrated how to execute a read transaction using the execute_read()
method.
The method handles transaction management automatically and allows for streaming results as they become available.
The execute_read()
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.