Return values in list of varying length as columns instead of rows

neo4j v 5.x dektop + apoc procedures:

My list activity has 3 items in the example below, but I might not know the length of the list in another run of the query.

I want to return the items in the list as columns and not rows, eg. something like:

WITH ["map1","map2","map3"] as activity
[i in range(0,size(activity)-1) | return activity[i]]

instead of manual

WITH ["map1","map2","map3"] as activity
return activity[0],activity[1], activity[2]

returning

Is that possible?

kr Kirsten

I don't think that's possible, but can be wrong. Would you mind explaining when this would be useful for you?

Best
/Love

I also don’t know of a way to do so. What is your use case? I generally would use a map.

Hi Gary and Love,

I want to present data in a tabular manner, and don't want to type the name of every column (also they could vary from query to query, i.e. more keys in my map), as I have them as keys (either as map keys or item in a list). It is like pivot or transpose of your data.

How would you do it using a map?

kr Kirsten

Well, you could create a map of key/value pairs giving a list of keys you want to return using an apoc function.

with {a:1, b:2, c:3, d:4} as map, ["a", "b"] as keys
return apoc.map.fromLists(keys, [key in keys | map[key]])

1 Like

I might be misinterpreting the ask, but you can use UNWIND to turn a list in to rows:

WITH ["map1","map2","map3"] as activity
UNWIND activity AS act
RETURN act

image

Thanks Gary! I just used this approach and it cut my runtime by over 50% (20.3s -> 8.8s). Part of that was because your approach cut down on the amount of data being transmitted, but it's still a nice gain.

If you're curious, here's the code comparison. Note: This was run from within python.

Original, bad query

Cypher returned a tall dataset, then used df.pivot() to get the fields as their own columns.

MATCH (n:Account)
UNWIND keys(n) AS Key
WITH collect(DISTINCT Key) AS Keys
MATCH (n:Account)
UNWIND Keys AS Key
RETURN n.acct_id, Key, n[Key] AS Value

Better method using APOC fromLists

Cypher returned each record as a dict (aka, map in Neo4j), which I could then easily convert into a dataframe.

MATCH (n:Account)
UNWIND keys(n) AS Key
WITH collect(DISTINCT Key) as Keys
MATCH (n:Account)
WITH Keys, n
RETURN apoc.map.fromLists(Keys, [key in Keys | n[key]]) AS Maps
1 Like