如何在列表中找到字符串的索引值 - 例如
WITH split ("what is porsche",' ')
我怎样才能找到保时捷的位置?为3?
答案 0 :(得分: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
答案 1 :(得分: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 :(得分:2)
正如布鲁诺所说,APOC是对此的正确要求,但如果由于某种原因你想找到没有APOC的职位,你可以通过以下的指导......
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
答案 3 :(得分:2)
在普通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)