Writing Data to Neo4j

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

  1. Create the Cypher statement that will create new a Person node and ACTED_IN relationship to The Matrix Movie node:

    typescript
        const cypher = `
          MATCH (m:Movie {title: "Matrix, The"})
          CREATE (p:Person {name: $name})
          CREATE (p)-[:ACTED_IN]->(m)
          RETURN p
        `
  2. Create the params object and set your name:

    typescript
        const params = { name: 'Your Name' }
  3. Execute the Cypher statement using the session.executeWrite() method:

    typescript
        const res = await session.executeWrite(
          tx => tx.run(cypher, params)
        )
  4. Log the result to the console:

    typescript
        console.log(res.records[0].get('p'))

Run the Challenge

Run the file using ts-node to view the result:

sh
ts-node src/challenges/write/challenge.ts

You can check the result in the Neo4j Browser by running the following query:

cypher
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:

ts
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()

Click here to view the solution on Github

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.