Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a composite object in Neo4j/Cypher

Tags:

neo4j

cypher

I'd like to return a composite object from Neo4j using cypher to tidy up my queries.

To give an example, I have a user account object that has permissions stored as relationships. The permissions are complex objects so can't be nested, they are now linked by the relationship [:HAS_PERMISSION]. What i'd like to do is return the full complex object with the permissions already nested, like in the example JSON object below

e.g.

permissions:
{
    action:'delete', 
    resource:'blog posts'
}
{
    action:'edit', 
    resource:'users'
}   

core user account:
{
  username:'Dave',
  email:'[email protected]'
}

What i'd like:
 {
  username:'Dave',
  email:'[email protected]'
  permissions: [{action:'delete', resource:'blog posts'},{action:'edit', resource:'users'}]
 }

The query I currently have:

MATCH(user:UserAccount)-[:HasPermission]->(permission:Permission)
WITH {user:user, permissions:collect(permission)} AS UserAccount
RETURN UserAccount

The problem is this doesn't quite return what i'm after, it returns this:

{
     user: {
     username:'Dave',
     email:'[email protected]'
     },
     permissions: [{action:'delete', resource:'blog posts'},{action:'edit', resource:'users'}]
 }

Please note: I'd really like to add the permissions list to the existing user object i'm returning please. I'd like to know how to save me having to explicitly declare all of the properties I need on the new object (if it's possible).

like image 494
David Swindells Avatar asked Jun 17 '16 09:06

David Swindells


2 Answers

You can design the objects as you need:

MATCH(user:UserAccount)-[:HasPermission]->(permission:Permission)
WITH { username:user.username, 
       email: user.email, 
       permissions:collect(permission)
     } AS UserAccount
RETURN UserAccount

Update

You can use apoc.map.setKey:

MATCH(user:UserAccount)-[:HasPermission]->(permission:Permission)
WITH user, collect(permission) as permissions
CALL apoc.map.setKey( user, 'permissions', permissions ) YIELD value as UserAccount
RETURN UserAccount
like image 187
stdob-- Avatar answered Nov 14 '22 04:11

stdob--


Since Neo4J 3.1 you can use Map projections

MATCH (user:UserAccount)-[:HasPermission]->(permission:Permission)
WITH user, collect(permission) as permissions
RETURN user{.*, permissions: permissions}
like image 23
Leo Rodríguez Avatar answered Nov 14 '22 04:11

Leo Rodríguez