Neo4j: Cypher - Create Cypher map with dynamic keys
I was recently trying to create a map in a Cypher query but wanted to have dynamic keys in that map. I started off with this query:
WITH "a" as dynamicKey, "b" as dynamicValue
RETURN { dynamicKey: dynamicValue } AS map
╒══════════════════╕
│"map" │
╞══════════════════╡
│{"dynamicKey":"b"}│
└──────────────────┘
Not quite what we want! We want dynamicKey to be evaluated rather than treated as a literal. As usual, APOC comes to the rescue!
In fact APOC has several functions that will help us out here. Let’s take a look at them:
CALL dbms.functions() yield name, description
WHERE name STARTS WITH "apoc.map.from"
RETURN name, description
╒═════════════════════╤═════════════════════════════════════════════════════╕
│"name" │"description" │
╞═════════════════════╪═════════════════════════════════════════════════════╡
│"apoc.map.fromLists" │"apoc.map.fromLists([keys],[values])" │
├─────────────────────┼─────────────────────────────────────────────────────┤
│"apoc.map.fromNodes" │"apoc.map.fromNodes(label, property)" │
├─────────────────────┼─────────────────────────────────────────────────────┤
│"apoc.map.fromPairs" │"apoc.map.fromPairs([[key,value],[key2,value2],...])"│
├─────────────────────┼─────────────────────────────────────────────────────┤
│"apoc.map.fromValues"│"apoc.map.fromValues([key1,value1,key2,value2,...])" │
└─────────────────────┴─────────────────────────────────────────────────────┘
So we can generate a map like this:
WITH "a" as dynamicKey, "b" as dynamicValue
RETURN apoc.map.fromValues([dynamicKey, dynamicValue]) AS map
╒═════════╕
│"map" │
╞═════════╡
│{"a":"b"}│
└─────────┘
or like this:
WITH "a" as dynamicKey, "b" as dynamicValue
RETURN apoc.map.fromLists([dynamicKey], [dynamicValue]) AS map
╒═════════╕
│"map" │
╞═════════╡
│{"a":"b"}│
└─────────┘
or even like this:
WITH "a" as dynamicKey, "b" as dynamicValue
RETURN apoc.map.fromPairs([[dynamicKey, dynamicValue]]) AS map
╒═════════╕
│"map" │
╞═════════╡
│{"a":"b"}│
└─────────┘
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.