Neo4j:拆分字符串并获取位置

时间:2016-05-09 07:30:11

标签: foreach split neo4j cypher

我需要将字段拆分为不同的值,并将每个值存储在不同的节点中。对于每个创建的节点,我想存储位置。 例如:

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

使用:

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

我可以分割字段并存储不同的字词,但我想在关系中存储位置。

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

我怎么能得到这个?

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]})

确保拳头WITH在第二个WITH WITH SPLIT(line.SWords, ";") AS SWords, line, s, ta

中包含必要的变量引用

2 个答案:

答案 0 :(得分:4)

您可以使用基于拆分大小的范围,假设包含该句子的节点标识为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)

更新

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]}) 

答案 1 :(得分:1)

使用范围:

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