当neo4j中2个节点具有相同的属性值时,如何为属性的重复值添加递增的整数?

时间:2017-09-14 18:18:52

标签: neo4j

在我的neo4j中,我有一个节点“Blog”,它具有属性“Title”。而“Title”属性对于2个不同的Blog节点可以具有相同的值。例如,

    Blog 
   {
    "Id": 1
    "Title":"Apple"
   },
   {
    "Id": 2
    "Title":"Apple"
    }

所以,尽管Id可能是唯一的,但“Title”属性可以具有相同的确切值“ Apple ”。如果存在相同的值,那么在这种情况下我想要添加最后一个节点的值(在Title属性中)的数字,如“ Apple 1 ”,Apple 2 ...... 这是我最新的代码......

Merge (D:Blog{ID:3})set D.Title = "Apple" with D
    // Collect all blogs with duplicate titles
MATCH (T:Blog)
WITH T.Title as title, 
     collect(distinct T) as blogs WHERE size(blogs) > 1

// Calculate the possible maximum start index for the title
OPTIONAL MATCH (T:Blog) 
WHERE size(T.Title) > size(title) AND T.Title STARTS WITH title
WITH title, 
     blogs,
     max(
       coalesce(
         toInteger(trim(
           substring(T.Title, size(title))
         )),
         0
       )
     ) + 1 as startIndex

// Rename all blogs except the first
UNWIND RANGE(1, size(blogs)-1) as i
WITH title + ' ' + (startIndex + i) as newTitle,
     blogs[i] as blog
SET blog.Title = newTitle
RETURN blog

我应该在cypher查询中执行此操作?我调查了apoc.do.when,但我无法弄明白。任何帮助都会很明显

1 个答案:

答案 0 :(得分:0)

// Get all blogs
MATCH (T1:Blog)
WITH T1.Title AS title, 
     // Then we collect all the blogs with the same titles, 
     // and remove the first one from the collection
     TAIL( COLLECT(DISTINCT T1) ) AS blogs
// Then we need to go through the cycle for the remaining blogs in the collection
UNWIND RANGE(1, size(blogs)) AS index
WITH title, 
     blogs[index] as blog,
     index
// And rename...
SET blog.Title= title+ ' ' + index
RETURN name, 
       blog

更新 |使用@InverseFalcon的评论来解决问题:

// Collect all blogs with duplicate titles
MATCH (T:Blog)
WITH T.Title as title, 
     collect(distinct T) as blogs WHERE size(blogs) > 1

// Calculate the possible maximum start index for the title
OPTIONAL MATCH (T:Blog) 
WHERE size(T.Title) > size(title) AND T.Title STARTS WITH title
WITH title, 
     blogs,
     max(
       coalesce(
         toInteger(trim(
           substring(T.Title, size(title))
         )),
         0
       )
     ) + 1 as startIndex

// Rename all blogs except the first
UNWIND RANGE(1, size(blogs)-1) as i
WITH title + ' ' + (startIndex + i) as newTitle,
     blogs[i] as blog
SET blog.Title = newTitle
RETURN blog