2017-09-26 82 views

回答

3

首先,位置将是2,因为我们通常从CS中的0开始。

这是一个班轮:

WITH split ("what is porsche",' ') AS spl 
RETURN [x IN range(0,size(spl)-1) WHERE spl[x] = "porsche"][0] 

返回2

WITH split ("what is porsche",' ') AS spl 
RETURN [x IN range(0,size(spl)-1) WHERE spl[x] = "is"][0] 

返回1

+0

我刚才用了一行 - 工作正常! – ugp

2

Cypher本身没有IndexOf-like函数。但是你可以安装APOC Procedure和使用功能apoc.coll.indexOf,就像这样:

WITH split ("what is porsche",' ') AS list 
RETURN apoc.coll.indexOf(list, 'porsche') 

结果将是:

╒════════════════════════════════════╕ 
│"apoc.coll.indexOf(list, 'porsche')"│ 
╞════════════════════════════════════╡ 
│2         │ 
└────────────────────────────────────┘ 

注:结果是2,因为指数从0开始

注2:请记得根据您使用的Neo4j版本安装APOC程序。看看version compatibility matrix

编辑:

而不使用APOC程序,用size()reduce()range()功能与CASE表达的一种可供选择的方法:

WITH split ("what is porsche",' ') AS list 
WITH list, range(0, size(list) - 1) AS indexes 
WITH reduce(acc=-1, index IN indexes | 
    CASE WHEN list[index] = 'porsch' THEN index ELSE acc + 0 END 
) as reduction 
RETURN reduction 

如果索引中没有找到然后-1将返回。

+2

我还致力于提供香草Cypher支架与列表理解的解决方案,但你打我到它。大! –

2

布鲁诺说,APOC是正确的呼吁这一点,但如果由于某种原因,你想找到没有APOC的位置,你可以经过以下rigamarole ...

WITH split("what is porsche",' ') AS porsche_strings 
UNWIND range(0,size(porsche_strings)-1) AS idx 
WITH CASE 
    WHEN porsche_strings[idx] = 'porsche' THEN idx + 1 
END AS position 
RETURN collect(position) AS positions 
2

实现此另一种方法in plain Cypher:

WITH 'porsche' AS needle, 'what is porsche' AS haystack 
WITH needle, split(haystack, ' ') AS words 
WITH needle, [i IN range(0, length(words)-1) | [i, words[i]]] AS word 
WITH filter(w IN word WHERE w[1] = needle) AS res 
RETURN coalesce(res[0][0], -1) 
+0

两种选择都很出色;然而布鲁诺第一次花了1ms,第二次花了18ms。再次,我印象非常深刻! – ugp

+2

感谢upvoting和接受这一点,但我不认为这应该是被接受的答案:-)。如果可以,请使用APOC。 –