FGY
FGY

Reputation: 67

Neo4j In Query with dynamic array

var arr = ["a","b","c","d"];
await session.run(`MATCH (x:Test WHERE x.name IN ${arr}`)

I use the neo4j database in nodeJs and I am writing queries but I am taking errors for arr, I tried many methods but I took arr not defined.

Upvotes: 0

Views: 142

Answers (2)

Parth
Parth

Reputation: 31

Try this,

var arr = ["a","b","c","d"];
await session.run(`MATCH (x:Test WHERE x.name IN ${JSON.stringify(arr)} `)

Upvotes: 0

stellasia
stellasia

Reputation: 5622

JavaScript is not formatting the string the way you would expect:

var arr = ["a", "b", "c", "d"]
let x = `MATCH (x:Test) WHRE x.name IN ${arr}`
console.log(x)

This prints:

"MATCH (x:Test) WHRE x.name IN a,b,c,d"

Which is not valid Cypher.

To overcome this issue, just let the Neo4j driver do the formatting for you by adding a parameter to your query:

await session.run(
    "MATCH (x:Test WHERE x.name IN $arr",
    {arr: arr},
)

Check reference for this syntax here.

Upvotes: 1

Related Questions