Nick Marinov
Nick Marinov

Reputation: 148

Neo4j console : Type mismatch: expected Collection<T> but was Node

I have a query that doesn't work. The error is:

Type mismatch: expected Collection but was Node coming from FOREACH..

Code:

MATCH (user:User {user_role: 'Customer'})
WITH user
OPTIONAL MATCH (user)-[hv:HAS_VAUCHER]->(v:Vaucher {status: 2})
WITH user, count(hv) as hv
WHERE hv = 0
WITH user
FOREACH (u IN user | CREATE (v:Vaucher {discount: 5, created_at: 1488531600, start_at: 1488531600, type: 'March', status: 2})<-[:HAS_VAUCHER]-(u))

I don't know where the error is.

Upvotes: 0

Views: 1199

Answers (3)

Tomaž Bratanič
Tomaž Bratanič

Reputation: 6514

you can shorten the filtering part with a WHERE NOT clause and simplify query like this

MATCH (user:User {user_role: 'Customer'}) 
where not (user)-[:HAS_VAUCHER]->(:Vaucher {status: 2})
CREATE (v:Vaucher {discount: 5, created_at: 1488531600, 
start_at: 1488531600, type: 'March', status: 2})<-[:HAS_VAUCHER]-(u)

Upvotes: 1

Nick Marinov
Nick Marinov

Reputation: 148

I made a further research and the way to do it was to create a collection:

MATCH (user:User {user_role: 'Customer'})
WITH user
OPTIONAL MATCH (user)-[hv:HAS_VAUCHER]->(v:Vaucher {status: 2})
WITH user, count(hv) as hv
WHERE hv = 0
WITH user, COLLECT(user) AS users
FOREACH (u IN users | CREATE (v:Vaucher {discount: 5, created_at: 1488531600, start_at: 1488531600, type: 'March', status: 2})<-[:HAS_VAUCHER]-(u))

the "user" when returned returns N nodes (not 1) but when passed to FOREACH it maybe takes only the first node.

Upvotes: 1

InverseFalcon
InverseFalcon

Reputation: 30397

While there are some improvements one could make to the query, here's a quick fix, dropping FOREACH since you don't have users in a collection, and you already have one user per row:

MATCH (user:User {user_role: 'Customer'})
WITH user
OPTIONAL MATCH (user)-[hv:HAS_VAUCHER]->(v:Vaucher {status: 2})
WITH user, count(hv) as hv
WHERE hv = 0
WITH user
CREATE (v:Vaucher {discount: 5, created_at: 1488531600, start_at: 1488531600, type: 'March', status: 2})<-[:HAS_VAUCHER]-(user)

Upvotes: 1

Related Questions