Executing queries

How do you execute a Cypher statement and access the results?

Execute the Cypher statement

Select the correct method to create an executable Cypher statement.

Java
final String cypher = """
    MATCH (m:Movie {title: $title})<-[:ACTED_IN]-(p)
    RETURN p.name AS actor
    """;
final String title = "Toy Story";

var result = driver./*select:executableQuery(*/
    cypher
    )
    .withParameters(Map.of("name", name))
    .execute();
  • ❏ cypher(

  • ✓ executableQuery(

  • ❏ execute(

  • ❏ verifyConnectivity(

Hint

The method to execute a Cypher query with the driver is the same one you used in the previous lesson - it starts with executable.

Solution

The correct answer is executableQuery(). This method creates an executable Cypher query which can be executed.

Java
var result = driver.executableQuery(cypher).execute();

Print the actor names

Select the correct method to print the name of each actor.

Java
final String cypher = """
    MATCH (m:Movie {title: $title})<-[:ACTED_IN]-(p)
    RETURN p.name AS actor
    """;
final String title = "Toy Story";

var result = driver.executableQuery(
    cypher
    )
    .withParameters(Map.of("name", name))
    .execute();

var records = result.records();
records.forEach(r -> {
        System.out.println(
            /*select:r.get("actor")*/
        );
    });
  • ❏ records.get("p.name")

  • ❏ records.get("actor")

  • ❏ r.get("p.name")

  • ✓ r.get("actor")

Hint

Review the RETURN clause in the Cypher statement.

Java
cypher = """
MATCH (m:Movie {title: $title})<-[:ACTED_IN]-(p)
RETURN p.name AS actor
"""

Solution

The name property of the p node is aliased as actor in the RETURN clause.

The get method of the Record object takes the alias as an argument.

Java
records.forEach(r -> {
    System.out.println(
        r.get("actor")
    );
});

Lesson summary

Nice work! You learned how to execute a Cypher statement and access the results.

In the next lesson, you will review how to transform the results.