How to check unique labels in a relationship?

MATCH (m)-[r:topicOf]->(n) RETURN distinct labels(m), distinct labels(n)

I want to return all unique labels with the relationship 'topicOf', but the above query gives this error:

Invalid input 'a': expected 'i/I' or 'o/O' (line 1, column 65 (offset: 64))
"MATCH (m)-[r:topicOf]->(n) RETURN distinct labels(m), distinct labels(n)"

How to modify it?

There's probably a simpler way, but I think this query returns what you want:

MATCH (m)-[r:topicOf]->(n)
WITH collect(m) AS m_nodes, collect(n) AS n_nodes
UNWIND m_nodes AS m
UNWIND labels(m) AS m_label
WITH n_nodes, collect(distinct m_label) AS m_labels
UNWIND n_nodes AS n
UNWIND labels(n) AS n_label
WITH m_labels, collect(distinct n_label) AS n_labels
RETURN m_labels, n_labels

I tire and It did the job.


Not tested

MATCH (m)-[:topicOf]->(n)
UNWIND labels(m) + labels(n) AS label <- You can combine lists even if the query fail
RETURN label

Note: Without context, this query might be grossly expensive.

Documentation link