Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the position of string in a list in Neo4j, Cypher

Tags:

neo4j

cypher

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?

like image 251
ugp Avatar asked Dec 12 '25 14:12

ugp


2 Answers

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

like image 67
Christophe Willemsen Avatar answered Dec 14 '25 03:12

Christophe Willemsen


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.

like image 42
Bruno Peres Avatar answered Dec 14 '25 04:12

Bruno Peres