Neo4j: Split string and get position

匿名 (未验证) 提交于 2019-12-03 00:44:02

问题:

I need to split a field in different values and store each value in a different node. For each created node I want to store the position. Example:

Sentence             Words My car is red        My;car;is;red 

Using:

FOREACH (w IN SPLIT(line.TWords, ";") |  MERGE (wd:Word {word: w}) 

I can split the field and store the different words, but I'd like to store the position on the relationship.

My car is red  -[HAS_WORD {position:1}]-> My My car is red  -[HAS_WORD {position:2}]-> car My car is red  -[HAS_WORD {position:3}]-> is My car is red  -[HAS_WORD {position:4}]-> red 

How can I get this?

SOLUTION

USING PERIODIC COMMIT LOAD CSV WITH HEADERS  FROM 'file:///output_2016-05-06_0203_Neo4jImport.csv' AS line FIELDTERMINATOR "\t"  MERGE (s:Segment{text: line.Source}) MERGE (ta:Segment{text: line.Target})  WITH SPLIT(line.SWords, ";") AS SWords, line, s, ta UNWIND RANGE(0, SIZE(SWords)-1) as i     MERGE (s)-[r:HAS_WORD {position:i+1}]->(w:Word {word: SWords[i]})  WITH SPLIT(line.TWords, ";") AS TWords, line, ta UNWIND RANGE(0, SIZE(TWords)-1) as i     MERGE (ta)-[r:HAS_WORD {position:i+1}]->(w:Word {word: TWords[i]}) 

Be sure that the fist WITH has the variable references necessary in second WITH: WITH SPLIT(line.SWords, ";") AS SWords, line, s, ta

回答1:

You can use a range based on the size of the split, assuming the node containing the sentence is identified with sentence :

WITH split(line.TWords, ';') as splitted UNWIND range(0, size(splitted) -1) as i MERGE (w:Word {word: splitted[i]}) MERGE (sentence)-[:HAS_WORD {position: i}]->(w) 

Update

USING PERIODIC COMMIT LOAD CSV WITH HEADERS  FROM 'file:///output_2016-05-06_0203_Neo4jImport.csv'  AS line FIELDTERMINATOR "\t"  MERGE (s:Segment{text: line.Source})  WITH SPLIT(line.SWords, ";") AS SWords, line  UNWIND RANGE(0, SIZE(SWords)-1) as i  MERGE (s)-[r:HAS_WORD {position:i+1}]->(w:Word {word: SWords[i]})  


回答2:

Use range:

MERGE (S:Sentence {text:"My car is red"})   WITH S, SPLIT(S.text, " ") as words   UNWIND RANGE(0,SIZE(words)-1) as i     MERGE (S)-[r:HAS_WORD {position:i+1}]->(w:Word {word: words[i]}) RETURN S, r, w 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!