In this challenge you will use write data to Neo4j to add yourself as an actor in The Matrix.
Open the src/challenges/write/challenge.ts
file that contains the starter code.
Steps
-
Create the Cypher statement that will create new a
Person
node andACTED_IN
relationship to The MatrixMovie
node:typescriptconst cypher = ` MATCH (m:Movie {title: "Matrix, The"}) CREATE (p:Person {name: $name}) CREATE (p)-[:ACTED_IN]->(m) RETURN p `
-
Create the
params
object and set your name:typescriptconst params = { name: 'Your Name' }
-
Execute the Cypher statement using the
session.executeWrite()
method:typescriptconst res = await session.executeWrite( tx => tx.run(cypher, params) )
-
Log the result to the console:
typescriptconsole.log(res.records[0].get('p'))
Run the Challenge
Run the file using ts-node
to view the result:
ts-node src/challenges/write/challenge.ts
You can check the result in the Neo4j Browser by running the following query:
MATCH (m:Movie {title: "Matrix, The"})<-[a:ACTED_IN]-(p:Person)
RETURN m, a, p
Verifying the Test
Once you have executed the code, click the Verify button and we will check that the code has been executed successfully.
Hint
To pass this challenge you must run the Cypher statement in a write transaction using the session.executeWrite()
method.
Solution
Compare your code with the solution here:
import dotenv from 'dotenv';
dotenv.config({ path: '.env' });
// Import the driver
import neo4j from 'neo4j-driver'
import { getNeo4jCredentials } from '../utils'
// Neo4j Credentials
const {
NEO4J_URI,
NEO4J_USERNAME,
NEO4J_PASSWORD
} = getNeo4jCredentials()
async function main() {
// Create a Driver Instance
const driver = neo4j.driver(
NEO4J_URI,
neo4j.auth.basic(NEO4J_USERNAME, NEO4J_PASSWORD)
)
// Open a new Session
const session = driver.session()
try {
// Create the Cypher statement
const cypher = `
MATCH (m:Movie {title: "Matrix, The"})
CREATE (p:Person {name: $name})
CREATE (p)-[:ACTED_IN]->(m)
RETURN p
`
// Define the parameters
const params = { name: 'Your Name' }
// Execute the `cypher` statement in a write transaction
const res = await session.executeWrite(
tx => tx.run(cypher, params)
)
console.log(res.records[0].get('p'))
}
finally {
// Close the session
await session.close()
}
}
main()
Lesson Summary
In this challenge, you used your knowledge to create a driver instance and run a Cypher statement.
Next, we will look at the Neo4j Type System and some of the considerations that you need to make when working with values coming from Neo4j in your TypeScript application.