Search code examples
neo4jcypher

Trying to filter an array of strings to return a single field which is a subset of the array with strings that contain a variable


The DB has items, and these items have a string parameter which is a comma separated string array. Im trying to pass in a search variable, and use that to return the item node, and the string array but with only the strings that match the search variable

match (n:Node) return n.string

returns the strings sorted by the item node as ["abc,def,abcde"]

match (n:Node)  where any(string in n.string where string contains "abc") return n

This gets me the nodes where one of the strings contains what I'm looking for, but I can't seem to find a way to get the ones which matched and return them as a field

So if a node has a string of ["abc","def","abcde"] then when I search for strings containing "bc" then it should get the node and return just the strings of ["abc","abcde"]


Solution

  • The following query returns each node and its list of filtered strings. Nodes without matching strings are ignored. $filter is a parameter with the desired filter (e.g., "abc").

    MATCH (n:Node)
    UNWIND n.string AS s
    WITH n, s
    WHERE s CONTAINS $filter
    RETURN n, COLLECT(s) AS filtered_strings
    

    NOTE: If n.string is actually a string that looks like a list, replace n.string with SPLIT(n.string, ',').