cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Connect all nodes in a group with each other

ldj20
Node Link

Say I have a group of nodes called "books" from some match statement like "MATCH(books:Book{year:2019})." I want to create a relationship between every pair of nodes in this group. So say "books" consists of book1, book2, and book3. I want to create these relationships:

book1
^    ^
|     \
V      V
book2<->book3

How would I do this?

4 REPLIES 4

Hi, I am not sure that is recommended but..

You can do this:

MATCH (b:Books {year: 2019})
MATCH (b1:Books {year: 2019})
where id(b)<>id(b1)
MERGE (b1)-[:MY_REL]->(b)
MERGE (b1)<-[:MY_REL]-(b)
return *

Results:
3X_a_4_a4a2d80cb43f5a5b67b9ff6d814c37931b98dc61.jpeg

I don't have the name of it right now, but look in the apoc documentation with the keyword link, there is a function explicitly build for that case.

ameyasoft
Graph Maven
Try this:

MATCH (b:Books {year: 2019})
with b order by id(b) ASC
with collect(b) as b2
CALL apoc.nodes.link(b2, 'MY_REL')
return b2

Benoit_d
Graph Buddy

as @SamChalvet said "I'm not sure that is recommended", I would like to add: it is rarely usable and make no sense.
It just slow down any performance without any advantages. And doubled both directed relationship is to avoid anyway.
The "least bad solution" is to create a top-node with label "Book_Label" and link all the book node to it with a "is_a" relationship. But it doesn't help a lot.
You will already have an ordered list of all books with the query

Match (b:Book)
Return b order by id(b)

Explain what you want to achieve.