How do you execute a Cypher statement and access the results?
Execute query with parameters
Complete the code to execute a query to find a person by name and return their birth year.
result, err := neo4j.ExecuteQuery(ctx, driver,
"MATCH (p:Person {name: $name}) RETURN b.born AS born",
/*select:map[string]any{"name": "Alice"} */,
neo4j.EagerResultTransformer,
)-
✓ map[string]any{"name": "Alice"}
-
❏ {"name": "Alice"}
-
❏ map[string]string{"name": "Alice"}
-
❏ []any{"name": "Alice"}
Hint
Parameters should be passed as a map with string keys and any values.
Solution
The correct answer is map[string]any{"name": "Alice"}.
result, err := neo4j.ExecuteQuery(ctx, driver,
"MATCH (p:Person {name: $name}) RETURN p.name AS name, b.born AS born",
map[string]any{"name": "Alice"},
neo4j.EagerResultTransformer,
)The Go driver expects parameters as map[string]any where keys are parameter names and values can be any type.
Specify database for query
You want to run the query on the "movies" database. Select the correct option to specify the database.
result, err := neo4j.ExecuteQuery(ctx, driver,
"MATCH (p:Person {name: $name}) RETURN p.name AS name",
map[string]any{"name": "Alice"},
neo4j.EagerResultTransformer,
/*select:neo4j.ExecuteQueryWithDatabase("movies")*/
)-
✓ neo4j.ExecuteQueryWithDatabase("movies")
-
❏ neo4j.SetDatabase("movies")
-
❏ neo4j.Database("movies")
-
❏ ExecuteQueryWithDatabase("movies")
Hint
The function you are looking for specifies which database to query when executing a query against in the context of the ExecuteQuery function.
Solution
The correct answer is neo4j.ExecuteQueryWithDatabase("movies").
result, err := neo4j.ExecuteQuery(ctx, driver,
"MATCH (p:Person {name: $name}) RETURN p.name AS name",
map[string]any{"name": "Alice"},
neo4j.EagerResultTransformer,
neo4j.ExecuteQueryWithDatabase("movies"),
)The ExecuteQueryWithDatabase() function is used to specify which database to query when executing a Cypher statement. It takes the database name as a string parameter.
Access query results
Select the correct way to access the "born" field returned by the query.
for _, record := range result.Records {
born, _ := record./*select:Get("born")*/
fmt.Println(born)
}-
❏ GetField("born")
-
✓ Get("born")
-
❏ Value("born")
-
❏ Field("born")
Hint
Use the method that retrieves a value by key from a record.
Solution
The correct answer is Get("born").
for _, record := range result.Records {
born, _ := record.Get("born")
fmt.Println(born)
}The Get() method retrieves a value by key from a record and returns both the value and a boolean indicating if the key exists.
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.