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

If successful, you should see output similar to the following (with your name instead of "Your Name"):

json
Expected Output
{
  identity: Integer { low: 12345, high: 0 },
  labels: [ 'Person' ],
  properties: { name: 'Your Name' },
  elementId: '4:abc123:12345'
}

You can also verify 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

You should see your Person node connected to The Matrix movie.

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,
  NEO4J_DATABASE
} = 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({ database: NEO4J_DATABASE })

  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

Troubleshooting

ts-node: command not found

If you receive a ts-node: command not found error, you can either:

  1. Install ts-node globally:

    sh
    npm install -g ts-node
  2. Or run via npx:

    sh
    npx ts-node src/challenges/write/challenge.ts
Cannot use import statement outside a module

This error occurs when Node.js tries to run TypeScript/ES modules as CommonJS. Ensure your tsconfig.json has the correct module settings, or run with:

sh
npx ts-node --esm src/challenges/write/challenge.ts
Verification fails but code works

If your code runs successfully and creates the node (you can see it in Neo4j Browser) but the verification fails:

  1. Ensure you are using the sandbox provided by GraphAcademy (not a local database)

  2. Check that the Person node was created with an ACTED_IN relationship to the movie titled "Matrix, The"

  3. Try refreshing the page and clicking Verify again

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.

Chatbot

How can I help you today?