slb
slb

Reputation: 781

How do you programmatically set a node's label in neo4jclient?

I have a string nodeType which needs to be stored in neo4j as a node's label. In Cypher, this would be

CREATE (n:nodeType)

where nodeType is a string set before this operation. In neo4jclient I have tried

.Create("(x:{type})")
.WithParam("type", nodeType)

but this is clearly not a correct usage of a parameter, and gives the error

Unhandled Exception: Neo4jClient.NeoException: SyntaxError:
Invalid input '{': expected whitespace or a label name
"CREATE (x:{type})"
           ^

Moving the label addition to a separate set operation gives the same error.

.Create("(x)")
.Set("x :{type}")
.WithParam("type", nodeType)

The official neo4jclient documentation on parameters says that "You can create parameters at any point in the fluent query..." but this does not seem to be the case, as the open bracket is not being treated as the start of a paramater by the Cypher engine. What am I doing wrong here?

Since string concatenation is a very, very bad idea, what is the intended method of setting a node's label from a variable in neo4jclient?

Upvotes: 0

Views: 468

Answers (2)

Charlotte Skardon
Charlotte Skardon

Reputation: 6270

Personally I would do:

var nodeType = "MyNode";
client.Cypher.Create($"(x:{nodeType})").ExecuteWithoutResults();

or if you can't use C# 6:

client.Cypher.Create(string.Format("(x:{0})", nodeType).ExecuteWithoutResults()

I think it's important to note here that neither of these is using string concatenation. This is what string.Format and string interpolation were designed to help with.

logisima is correct that you can't do it via Cypher and your only option would be to shift to APOC if you do need to do it that way, but the string options would be far easier to use

Upvotes: 1

logisima
logisima

Reputation: 7458

Labels can't be parameterized in a cypher query. To create a node with a dynamic label, you can use APOC with this procedure : CALL apoc.create.node(['Label'], {key:value,…​})

Upvotes: 1

Related Questions