0

I need to return nodes along with their IDs, and things like this are to be avoided:

RETURN n, ID(n) as n_ID

I would very much prefer to be able to return the ID as a "computed" property of the node, so that the client sees the node as if it had a property named id.

I've been breaking my head over this for hours now. The closest I found is this comment under an unsatisfying answer to a similar question:

MATCH (n:Person) RETURN { id: ID(n), name: n.name } as user

That method is useless because it requires manually reconstructing the node as a map literal in the RETURN clause. This is impossible if you don't know all the property names, which will be the typical scenario in my application; plus, there might be lots of properties.

Next thing I tried was operator '+'. It throws a Type Mismatch; you cannot combine a Map with a Node this way. I cannot find any documented way to convert a Node to a Map either. The docs mention KEYS(), but no VALUES(), nor a way to "zip" keys and values into a map.

Another thing I thought of trying:

REDUCE(theMap = {id: ID(n)}, k in KEYS(n) | theMap + { what? : what? })

... but I know neither how to do a "variable key" in an array literal, nor how to access a node's property by a variable key.

Is what I am trying to do at all possible in cypher?

Community
  • 1
  • 1
Szczepan Hołyszewski
  • 2,707
  • 2
  • 25
  • 39

2 Answers2

0

You can add the id property right after you CREATE a node (and in the same transaction). For example:

CREATE (n:Person {name: "Fred", address: "123 Main St"})
SET n.id = ID(n)
RETURN n;

This way, your nodes will actually have an id node -- there is no need to compute it later.

cybersam
  • 63,203
  • 6
  • 53
  • 76
  • This tastes like defeat but might indeed be the only way... sad how unorthogonal Cypher is. Features that are very similar conceptually (both nodes and maps are key-value pairs) stubbornly refuse to work together. – Szczepan Hołyszewski Dec 23 '15 at 05:15
0

Depending on what you are doing with the id, you might want to reconsider returning the Neo4j node id (the internal id) and instead generate and store a UUID property on each node. Internal node ids can be reused and should not be used to reference nodes in an external system. Internal ids represent an offset in the store file and if nodes are deleted these gaps in the store file can be filled in, reclaiming already used ids.

There is a plugin here that can automate UUID creation and a discussion on Github here.

William Lyon
  • 8,371
  • 1
  • 17
  • 22