Optional merge on relationships

Viewed 2283

I am new to Cypher and I am trying to learn it through a small project I am trying to set up.

I have the following data model so far: enter image description here

For every Thought created, I connect Tags through Categories. The Categories only serve as intermediate between the Tags and Thoughts, this is done to improve querying, prevent Tag duplication and reduce relationships between the objects.

To prevent creation of new Tags with the same value, I thought of the following query:

CREATE (t: Thought {moment:timestamp(), message:'Testing new Thought'})
MERGE (t1: Tag{value: 'work'})
MERGE (t2: Tag{value: 'tasks'})
MERGE (t3: Tag{value: 'administration'})
MERGE (c: Category)
MERGE (t1)<-[u:CONSISTS_OF{index:0}]-(c)
MERGE (t2)<-[v:CONSISTS_OF{index:1}]-(c)
MERGE (t3)<-[w:CONSISTS_OF{index:2}]-(c)
MERGE (t)-[x:CATEGORIZED_AS{index: 0}]->(c)

This works fine, except for one thing: the Thought receives a relationship with all created Categories. This I understand, I define no restrictions in the MERGE query.

However, I do not know how to apply restrictions to the CATEGORIZED_AS relationship?

I tried to add this to the bottom of the query, but that does not work:

WHERE (t)-[x]->(c)

Any idea how to apply a restriction like I need in my case?

EDIT:

I forgot to mention the unique connection of a Category: A category is connect to a fixed set of Tags in a specific order.

E.g I have three tags:

  • work
  • tasks
  • administration

The only way the Category matches the Thought is if the Category has the following relationships with the Tags:

  • work <-[:CONSISTS_OF {index:0}]-(category)
  • tasks <-[:CONSISTS_OF {index:1}]-(category)
  • administration <-[:CONSISTS_OF {index:2}]-(category)

Any other order of relationships is invalid and a new Category should be created.

2 Answers
Related