0
votes

I have a problem with my cypher query.

Situation explained: A user is able to connect to other CONTACT nodes, but he can also connect to EVENT nodes. Other users can also connect to these event nodes. We expect to retrieve the nodes we are connected to (CONTACT & EVENT) but we also need to retrieve the event nodes of the CONTACT nodes that we are connected to.

This is the graph we want to see when we retrieve the connected nodes from the bottom center CONTACT node:

neo4j graph

But we receive this json output:

{
  "_type": "Node",
  "_id": 1,
  "nodeType": "EVENT",
  "nodeId": 1,
  "connected_with": [
    {
      "_type": "Node",
      "_id": 0,
      "nodeType": "CONTACT",
      "nodeId": 1
    },
    {
      "_type": "Node",
      "_id": 2,
      "nodeType": "CONTACT",
      "nodeId": 2,
      "connected_with": [
        {
          "_type": "Node",
          "_id": 0,
          "nodeType": "CONTACT",
          "nodeId": 1
        }
      ]
    }
  ]
}

We want to go 2 levels deep, meaning we want to see contacts that we are connected to but also contacts we "met" at an event hence the reason we want to go 2 levels deep.

We currently have this cypher query running but as previously mentioned, it's not working.

MATCH path = (n:Node {nodeId: 1})<-[:CONNECTED_WITH*]-(nodes)
WITH collect(path) as paths
CALL apoc.convert.toTree(paths) yield value as json
RETURN json

Any help would be appreciated!

1

1 Answers

0
votes

Your results seem to match what you say you want, except that it is in tree form (which you asked for).

You state that you do not "see" what you expected (presumably in the neo4j Browser). This is because the results you asked for are not plain nodes, relationships, and/or paths.

Try this, instead (note also the upper bound of 2 on the depth of the variable-length path pattern):

MATCH path = (n:Node {nodeId: 1})<-[:CONNECTED_WITH*..2]-(nodes)
RETURN path

Aside: Having just a single node label, Node, with a nodeType property that specifies the exact "type" of node is not generally the right way to model things. It makes it harder to understand the DB, tends to complicate your code, and makes it harder to take advantage of indexing. You probably want to have separate labels (say, Person and Event). You may also want to have different relationship types as well.