Martin Levine
Martin Levine

Reputation: 27

Relationship types as variables

I want the relationship label to be "xxxyyy" the combination of the nodes, or even xxx_yyy, "+" is string concatenation or set up a variable as x = a.name + b.name but what I try or have looked up fails.

Appears no quotes or dollar sign in relationship label, could save me a lot of typing.

MATCH (a:book),(b:story)
WHERE a.Name = "xxx" AND b.Name = "yyy"
CREATE (a)-[r:a.name+b.name]->(b)
RETURN r

Upvotes: 1

Views: 1396

Answers (2)

cybersam
cybersam

Reputation: 66947

Let's say there are S story names, and on average every story has B book names. That would give you S * B relationship types. It is not good practice to create that many relationship types, especially when the type names incorporate actual data values. In fact, the lack of Cypher support for what you wanted to do is an indication that it is a bad practice.

A relationship type name should should indicate a "type of relationship" -- and not be so granular as to denote a "specific individual relationship". Instead, to find a specific relationship, you should use its type name, and its the property values and/or the property values of the nodes it connects.

Here are some examples of what you might want to do instead.

Create a CONTAINS relationship between a book and a story (for better performance, you should also create indexes on :book(Name) and :story(Name))):

MATCH (b:book),(s:story)
WHERE b.Name = "xxx" AND s.Name = "yyy"
CREATE (b)-[r:CONTAINS]->(s)
RETURN r;

To get all the books that contain a specific story:

MATCH (b:book)-[:CONTAINS]->(s:story)
WHERE s.Name = "yyy"
RETURN b;

To get all the stories contained in a specific book:

MATCH (b:book)-[:CONTAINS]->(s:story)
WHERE b.Name = "xxx"
RETURN s;

To verify that a specific book contains a specific story, and get them:

MATCH (b:book)-[:CONTAINS]->(s:story)
WHERE b.Name = "xxx" AND s.Name = "yyy"
RETURN b, s;

Upvotes: 2

William Lyon
William Lyon

Reputation: 8546

This is not possible in plain Cypher, but you can use the apoc.create.relationship procedure to accomplish this:

MATCH (a:book),(b:story) 
WHERE a.Name = "xxx" AND b.Name = "yyy" 
CALL apoc.create.relationship(a, a.name + b.name, {}, b)

Upvotes: 5

Related Questions