Connect all nodes in a group with each other

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?

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:
Image 2021-08-13 at 13.35.29

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.

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

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.

1 Like