Stephen D
Stephen D

Reputation: 3076

How to find a subset of nodes and return their id's in cypher?

I am trying to write a cypher query which allows you to pass in a set of names as strings to find matching nodes and then return each node's id. I've been playing around with the language and came up with the following flawed query:

START person=node(*)
WHERE HAS (person.name)
WITH FILTER (name IN ['ryan','mike'] : person.name=name) AS matchedPersons
RETURN ID(matchedPersons)

Expected `matchedPersons` to be a node or relationship, but it was ``

If I return matchedPersons instead of ID(matchedPersons), I get this result:

+------------------------------------------+
| matchedPersons                           |
+------------------------------------------+
| ["ryan"] |
| ["mike"] |
| []                                       |
+------------------------------------------+
3 rows

In my database, I have three person nodes that have the names 'ryan', 'mike', and 'lucy'. I want to get the ID's of the people that match the names in the collection defined in the FILTER clause. How can I get the ID's of each person who has a name that matches at least one of the names in the collection?

Upvotes: 1

Views: 1002

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18002

There's a much simpler way to write this query:

neo4j-sh (?)$  match (p:Person) where p.name in ['ryan', 'mike'] return id(p);
+-------+
| id(p) |
+-------+
| 14680 |
| 14681 |
+-------+
2 rows
96 ms

(Tested on some local data, so your IDs will be different).

OK, so that's how to do it. But here's the thing - you probably shouldn't look at, deal with, or care about the IDs of individual nodes. See this related question. Node IDs should be thought of as an implementation detail. All they'll ever do for you is provide a unique identifier, but you should make zero assumptions about what their value will be. Don't make assumptions like that they'll never change, or that they're always ordered in a certain way. If you need an identifier with actual meaning, use your own.

Upvotes: 2

Related Questions