Lee Jack
Lee Jack

Reputation: 191

Neo4j : How to create a unique node instead of set of nodes

I want to create a new node (event nodes) among a set of nodes (report nodes) according to the indicator nodes (each report node has several indicator nodes related to it). I want to set the new event nodes with the rules:

  1. a report nodes is only connected one event node
  2. if more than one indicator nodes has the same property "pattern", then they belong to the same event node

here are my query code :

OPTIONAL MATCH 
(indicator_1_1:indicator)<-[:REFERS_TO]-(report_1:report)-[:REFERS_TO]->(indicator_1_2:indicator),
(indicator_2_1:indicator)<-[:REFERS_TO]-(report_2:report)-[:REFERS_TO]->(indicator_2_2:indicator)
WHERE
indicator_1_1.pattern=indicator_2_1.pattern
and
indicator_1_2.pattern=indicator_2_2.pattern
MERGE
(report_1)-[:related_to]->(event:EVENT)<-[:related_to]-(report_2)

and get the result as below, enter image description here

But i want the three report nodes belong to one event node. I want to know what changes should I make to my query ,or what next step should I take after getting the two event nodes.

What's more , I want to know wheter there is a more efficient query code than mine.

Thanks!

Upvotes: 2

Views: 135

Answers (2)

rickhg12hs
rickhg12hs

Reputation: 11902

I don't have any data to confirm, but I think a small change to your Cypher query will produce what you want.

From the Neo4j Cypher Manual chapter on MERGE (my emphasis added).

When using MERGE on full patterns, the behavior is that either the whole pattern matches, or the whole pattern is created. MERGE will not partially use existing patterns — it’s all or nothing. If partial matches are needed, this can be accomplished by splitting a pattern up into multiple MERGE clauses.

So, following this, I think if you change

MERGE (report_1)-[:related_to]->(event:EVENT)<-[:related_to]-(report_2)

to

MERGE (report_1)-[:related_to]->(event:EVENT)
MERGE (event)<-[:related_to]-(report_2)

... you will prevent the extra :EVENT nodes from being created and get the graph you are looking for.

Upvotes: 1

Lee Jack
Lee Jack

Reputation: 191

Finally, I find the answer. My solution is merge the :event node ,and then the relaionships

step 1 : merge the :event nodes

MATCH ()-[r_1:related_to]->(event_1:EVENT)<-[r_2:related_to]-()-[r_3:related_to]->(event_2:EVENT)<-[r_4:related_to]-()
call apoc.refactor.mergeNodes([event_1,event_2]) YIELD node
RETURN node

step 2 : merge the dupicate relationships

MATCH (X)-[r]-(Y)
WITH X,Y, TAIL (collect(r)) as rr
FOREACH (r IN rr | DELETE r)

Upvotes: 0

Related Questions