'NEO4J: ADDING constrained label only to first iteration met

I am starting with a MATCH of n:INITIAL and want to add n:ADDLABEL to only first iteration I meet, as I have a constraint on n.prop of n:ADDLABEL (of many pre-existing n:ADDLABEL). I may get duplicate n.prop:INITIAL iterations, so I would run into the constraint the second time I want to add the label because it will have been added the first time around. Ideally I'd like to know which condition is met so I can choose paths accordingly. How do I go about this?

This gives a sense for what I'm trying to do, but the first foreach gives an error whenever n:INITIAL holds duplicate n.props.

MATCH (n:INITIAL)
OPTIONAL MATCH (existingLabel:ADDLABEL {prop: n.prop})
OPTIONAL MATCH (otherInitial:INITIAL {prop: n.prop}) WHERE NOT otherInitial=n

WITH DISTINCT n, existingLabel, otherInitial
FOREACH (o1 IN CASE WHEN existingLabel IS NULL THEN [1] ELSE [] END |
   
     FOREACH (x1 IN CASE WHEN otherInitial IS NULL THEN [1] ELSE [] END |
           SET n:ADDLABEL )
    
     FOREACH (x2 IN CASE WHEN NOT otherInitial IS NULL THEN [1] ELSE [] END |
           // SET n:ADDLABEL on first
           // MERGE (n)-[:DUPLICATE_OF]->(first) on second
)

FOREACH (o2 IN CASE WHEN NOT existingLabel IS NULL THEN [1] ELSE [] END |
   MERGE (n)-[:DUPLICATE_OF]->(existingLabel)   
)


How do I apply n:ADDLABEL only on first node of any duplicates? I'm trying to save database space by having the :INITIAL and :ADDLABEL overlap but I guess maybe it would be better to separate them after all...

I was very hopeful that apoc.cypher.doIt would be the answer to iterate over each query as though it were brand new and the previous one was committed, but that also yields error "IndexEntryConflictException"... so disappointing!

MATCH (n:INITIAL)

CALL apoc.cypher.doIt(“
OPTIONAL MATCH (existingLabel:ADDLABEL {prop: n.prop})

FOREACH (o1 IN CASE WHEN existingLabel IS NULL THEN [1] ELSE [] END |   
      SET n:ADDLABEL )

FOREACH (o2 IN CASE WHEN NOT existingLabel IS NULL THEN [1] ELSE [] END |
   MERGE (n)-[:DUPLICATE_OF]->(existingLabel)   

RETURN n as n”,

{n:n}) YIELD value as n2

Never mind - the latter DOES work. I had a typo. So ANSWER: use apoc.cypher.doIt. Don't you love how just posting a question makes you find the answer?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source