Append node to a collection

Hi ,
i am trying to return a collection of nodes and append another single node at the end of the collection. If the collection is empty, then i want it to return the single node (if its not null), however my current query returns empty whenever the reversedCollection is empty, eventhough the node "e" still exists. How do i write the query?

MATCH (ws:Workspace {wsId:1})-[:OP*]->(e:Event {elementId:276})
WITH e LIMIT 1
MATCH p=(e)-[:ELEMENT_276*]->(root:Event)
WITH reverse(collect(root)) AS reversedCollection, e
RETURN reversedCollection + [e] AS foundElementEvents

Bewlow query did also not help as it returns an empty list.

MATCH (ws:Workspace {wsId:1})-[:OP*]->(e:Event {elementId:276})
WITH e LIMIT 1
MATCH p=(e)-[:ELEMENT_276*]->(root:Event)
WITH reverse(collect(root)) AS reversedCollection, e
RETURN
CASE 
    WHEN size(reversedCollection)>0 THEN reversedCollection + [e]
    ELSE [e] 
END AS result

I appreciate any help.
BR

The query the way it is written should return nothing when the match does not return a result, since the collect will not return empty when there is a grouping variable ('e'). An approach to get around this is to use list comprehension instead. Try the following:

MATCH (ws:Workspace {wsId:1})-[:OP*]->(e:Event {elementId:276})
WITH e LIMIT 1
RETURN reverse([(e)-[:ELEMENT_276*]->(root:Event)|root]) + [e]

I do have a question about your query. You are describing the specific node 'e' you want via the elementId. As such, why do you need to match it in a pattern? Are you trying to also ensure it has a path to the specified Workspace node? If so, you may want to use an "exists" predicate instead, as this will find the first path and stop the search and it will also not return paths for all the match if more than one exists. Something like this:

MATCH (e:Event {elementId:276})
WHERE EXISTS( (:Workspace {wsId:1})-[:OP*]->(e) )
RETURN reverse([(e)-[:ELEMENT_276*]->(root:Event)|root]) + [e]
1 Like

hey gary,

i am doing a pattern because in my graph i can have multiple event nodes with this same id (and these are connected with relationship name "ELEMENT_{elementID}" ), and what i am trying to get is the path from the first found event node with id=276, and then go along the path and take all those events that are connected to this event through the relationship [:ELEMENT_276*]... but sometimes there is only one single event (e) and in that case i just want to return that event

The first query you suggested has worked. Thank you very much for your solution :smiley:
BR

1 Like