Search code examples
neo4jcypher

Cypher query for Neo4j error "Variable not defined"


I am playing with Neo4j and am trying to implement a "is in set" data structure. In my example project I create an item with the name "iPhone" and want to create a relationships ("is in") with the category "Cell Phones & Accessories". When I execute the below Cypher query I receive the error: "Variable 'b' not defined (line 1, column 51 (offset: 50))".

Query throws an error

CREATE (a:Item {name:'iPhone 12'}) WITH a, MATCH (b:Category) WHERE b.name='Cell Phones & Accessories' CREATE (a)-[r:in]->(b)

If I instead run two separate queries (see below), it works, but this is inefficient and I would like to understand what I'm doing wrong.

Separate queries work

CREATE (a:Item {id:'5'})

and,

MATCH (a:Item),(b:Category) WHERE a.id='5' AND b.name='Cell Phones & Accessories' CREATE (a)-[r:in]->(b)

What I have tried

I have found this and many similar discussion where the variable simply wasn't passed in the WITH statement, but in my case this does not apply as far as I understand.

Thankful for every response :)


Solution

  • Please remove the comma after WITH a, then it will work.

    CREATE (a:Item {name:'iPhone 12'}) 
    WITH a    #removed the comma here
    MATCH (b:Category) WHERE b.name='Cell Phones & Accessories' 
    CREATE (a)-[r:in]->(b)