我将如何找到一个列表中字符串的索引值 - 例如查找在Neo4j的列表串的位置,Cypher支架
WITH split ("what is porsche",' ')
我将如何找到“保时捷”为3的位置?
我将如何找到一个列表中字符串的索引值 - 例如查找在Neo4j的列表串的位置,Cypher支架
WITH split ("what is porsche",' ')
我将如何找到“保时捷”为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
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将返回。
我还致力于提供香草Cypher支架与列表理解的解决方案,但你打我到它。大! –
布鲁诺说,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
实现此另一种方法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)
两种选择都很出色;然而布鲁诺第一次花了1ms,第二次花了18ms。再次,我印象非常深刻! – ugp
感谢upvoting和接受这一点,但我不认为这应该是被接受的答案:-)。如果可以,请使用APOC。 –
我刚才用了一行 - 工作正常! – ugp