How do I filter a List in Memgraph cypher?

39 Views Asked by At

How can I filter this this list so as to keep only items over 3? [1,2,3,4,5]

Memgraph does not seem to have a FILTER clause nor a filter function on the collections module. I'm unable to figure out how the extract or the reduce functions can help.

Can anybody help me filter out my frustration ;) ?


I got this to work, but is there a better way?

with [1,2,3,4,5] as list
unwind list as l 
with l
where l>3
return collect(l) 
1

There are 1 best solutions below

0
KateLatte On

I wrote a small custom procedure in Python, directly in Memgraph Lab which might help:

import mgp

@mgp.read_proc
def filter(
  context: mgp.ProcCtx,
  my_list: mgp.List[mgp.Any],
  threshold: int
) -> mgp.Record(reduced_list=mgp.List[mgp.Any]):


  reduced_list= [num for num in my_list if num > threshold]

  return mgp.Record(
    reduced_list=reduced_list,
  )

Here's how to call it:

WITH [1,2,3,4,5] as list
CALL transform_list.filter(list, 3)
YIELD reduced_list
RETURN reduced_list;

And here are the instructions on how to create it in Memgraph Lab.