How would i find the index value of a string within a list - for example
WITH split ("what is porsche",' ')
how would I find the position of 'porsche' as 3?
First of all, the position would be 2 as we generally start from 0 in CS.
This is a one liner :
WITH split ("what is porsche",' ') AS spl
RETURN [x IN range(0,size(spl)-1) WHERE spl[x] = "porsche"][0]
Returns 2
WITH split ("what is porsche",' ') AS spl
RETURN [x IN range(0,size(spl)-1) WHERE spl[x] = "is"][0]
Returns 1
Cypher does not have an IndexOf-like function natively. But you can install APOC Procedure and use the function apoc.coll.indexOf, like this:
WITH split ("what is porsche",' ') AS list
RETURN apoc.coll.indexOf(list, 'porsche')
The result will be:
╒════════════════════════════════════╕
│"apoc.coll.indexOf(list, 'porsche')"│
╞════════════════════════════════════╡
│2 │
└────────────────────────────────────┘
Note: The result is 2 because indexes starts at 0.
Note 2: Remember to install APOC Procedures according the version of Neo4j you are using. Take a look in the version compatibility matrix.
EDIT:
One alternative approach without using APOC Procedures, using size(), reduce() and range() functions with CASE expression:
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
In case the index is not found then -1 will return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With