SET label : pass label name as parameter

2019-08-04 18:10发布

问题:

I have a query like this:

unwind {data} as row with row MERGE (p:Book{guid:row.bookGuid}) set p.name=row.name, p:Science

I want to pass the label 'Science' as a parameter as this label is not same for all the rows which I am passing in {data}.

I tried below query, but this is throwing syntax error.

with parameter like: { guid:1, name:"testName1",label1:"Histroy"}

unwind {data} as row with row MERGE (p:Book{guid:row.bookGuid}) set p.name=row.name, p:row.label1

Any workaround?

Thanks

回答1:

You can use APOC apoc.create.addLabels():

UNWIND {data} as row WITH row
MERGE (p:Book{guid:row.bookGuid})
SET p.name=row.name
CALL apoc.create.addLabels(id(p), [row.label1])

Another example: Using Cypher and APOC to move a property value to a label



回答2:

Yeh it's not supported yet. If you want to make it work you have to do a bit of a hack using FOREACH which you'll have to do for each type of label:

unwind {data} as row with row 
FOREACH(ignoreMe IN CASE WHEN row.label = "Science" THEN [1] ELSE [] END |
    MERGE (p:Book:Science{guid:row.bookGuid}) 
    set p.name=row.name
)

FOREACH(ignoreMe IN CASE WHEN row.label = "Math" THEN [1] ELSE [] END |
    MERGE (p:Book:Math{guid:row.bookGuid}) 
    set p.name=row.name
)

And so on...



回答3:

I guess that you could structure your data differently:

(:Book {guid, name})-[:HAS_LABEL]->(:Label {name})

In this way you could use the label name as parameter in CREATE or MATCH queries. Your original query would be:

UNWIND {data} as row WITH row 
MERGE (p:Book {guid: row.guid})
MERGE (l:Label {name: row.label})
CREATE UNIQUE p-[:HAS_LABEL]->l
SET p.name = row.name