Dynamically filling in label in a query gives an error

In the query below I am passing in two strings, $node and $targetlabel. The first one works, the second creates an error.

		query := `MATCH ({name:$node})-[e]-(n:$targetlabel) RETURN DISTINCT n.name as name, n.detail as detail, TYPE(e) as link`
		records, err := tx.Run(query, map[string]interface{}{
			"node":        node,
			"targetlabel": targetlabel,
		})

I get the error:

2022/01/17 21:39:11 error querying node: Neo4jError: Neo.ClientError.Statement.SyntaxError (Invalid input '$': expected an identifier (line 1, column 29 (offset: 28))
"MATCH ({name:$node})-[e]-(n:$targetlabel) RETURN DISTINCT n.name as name, n.detail as detail, TYPE(e) as link"
                             ^)

The query works just fine when I replace $targetlabel with the actual label. Am I doing something wrong?

Hi @adamsits

Parameters cannot be used for the labels.

2 Likes

What I do in this scenario is format the cypher string with the label condition before passing to the query. In Java, I do the following:

String cypher = String.format("match(n) where n:%s return n", label.cypherLabel);

the label I want gets replaced in the where clause. You could add it in the node as well:

String cypher = String.format("match(n:%s) return n", label.cypherLabel);

2 Likes