cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Optional parameters

Hello guys!

I have the following query

MATCH (u: User)<-[:USER_PERMISSION]-(p: Permission) 
WHERE ID(u)=$userId
RETURN p

I get user and its permissions by userId, simple.
I want to query by name if permissionName is passed in params and if not I just dont put in the where

MATCH (u: User)<-[:USER_PERMISSION]-(p: Permission) 
WHERE ID(u)=$userId AND IF($permissionName ? p.name STARTS WITH $permissionName  : "")
RETURN p

How would I be able to do this?

1 ACCEPTED SOLUTION

I see an easy patch to my request:

MATCH (u: User)<-[:USER_PERMISSION]-(p: Permission) 
WHERE ID(u) = $userId
AND p.name STARTS WITH coalesce($permissionName, p.name)
RETURN p

View solution in original post

4 REPLIES 4

Hello @djole.nikolic.priv

MATCH (u: User)<-[:USER_PERMISSION]-(p: Permission) 
WHERE ID(u) = $userId
AND p.name STARTS WITH coalesce($permissionName, "")
RETURN p

Regards,
Cobra

Thank, but it doesn't seem to work. I get empty result.

$permissionName will be passed all the time, but I want that if the $permissionName is null, to ignore that part of where clause and return all names.

I will use other params as well, and I want same behavior. For example filtering by action:

IF ($action NOT NULL) p.action=$action ELSE p.action can be anything

I would need something like:

AND p.name STARTS WITH coalesce($permissionName, ANYTHING)

I see an easy patch to my request:

MATCH (u: User)<-[:USER_PERMISSION]-(p: Permission) 
WHERE ID(u) = $userId
AND p.name STARTS WITH coalesce($permissionName, p.name)
RETURN p

AWESOME, exactly what I need.
Nice style of thinking.
Using same logic for IN

AND ID(p) IN coalesce($permissionIds, [ID(p)])

And it works.
They should put this in the docs tbh..such a powerful method for optional filters.
I actually used JS to parse the string and remove them, but this is way better
Thanks a lot!!!!