James Newton
James Newton

Reputation: 7104

Cypher: WITH is required between CREATE and MATCH

I want to create a group of nodes, and get the result of the CREATE statement. If I do this in the Neo4j browser...

CREATE (a:Group {name: "a"})
     , (b:Group {name: "b"})
     , (c:Group {name: "c"})
MATCH (r:Room)
RETURN r

... I get a Neo.ClientError.Statement.InvalidSyntax error: WITH is required between CREATE and MATCH.

I don't get this error if I create a dummy WITH statement...

CREATE (a:Group {name: "a"})
     , (b:Group {name: "b"})
     , (c:Group {name: "c"})
WITH a as a
MATCH (r:Room)
RETURN r

... or if I break this up into 2 separate queries, first...

CREATE (a:Group {name: "a"})
     , (b:Group {name: "b"})
     , (c:Group {name: "c"})

... then...

MATCH (r:Room)
RETURN r

Can you help me to understand what the WITH statement is doing and why it is essential if I create a single query?

Upvotes: 1

Views: 4061

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18022

So basically what WITH does is that it lets you chain together two different queries. This is useful because it helps cut down on the amount of computation required to answer the query.

Your query is a bit strange:

CREATE (a:Group {name: "a"})
     , (b:Group {name: "b"})
     , (c:Group {name: "c"})
WITH a as a
MATCH (r:Room)
RETURN r

What's strange about this is that there's no variable in common between CREATE and MATCH. It seems more here that you're using WITH to run two unrelated queries as one statement. That's fine, but I think WITH is awkward for you because that's not how it was intended to be used.

The link I posted at the top gives specific reasons why you'd want to use WITH. (Limiting the branching of your search path, and sorting results before you process more of them being examples).

For your particular query, I would have tended to break the CREATE and the MATCH into two different queries, so no surprise that WITH seems odd here. Here's a different example of a query you could have run, where it would make more sense:

MATCH (g:Group)
WHERE g.prop = "foo" /* some condition, only some groups */
WITH g
CREATE (g)-[:rel]->(another:Group)
WHERE another.prop = "bar";

So that query would match only certain groups, then create relationships to other groups - with WITH help makes it clear that the new relationships being created are limited to only those things that matched in the earlier steps.

Hope this helps.

Upvotes: 1

Related Questions