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?

Hello @djole.nikolic.priv :slight_smile:

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
1 Like

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!!!!

1 Like