简体   繁体   中英

Cypher - Convert graph result to list or JSON

I have the following Neo4j graph result.

Neo4j图结果
I 'm using the multiple relationship -[RELATED_TO*]- command to obtain that.

Match(n:Comment)
MATCH(n)-[RELATED_TO*]-(d:Comment)
return n, d;

I want to display the results in a List where I could say that this answer comes from that answer, or in a JSON cascade file. What is the best approach to reach that?

I think you can return a JSON cascade structure using the APOC procedure apoc.convert.toTree . Take a look in this example:

Creating a sample data set:

CREATE (:Comment {id : 1})<-[:RELATED_TO]-(:Comment {id : 2})<-[:RELATED_TO]-(:Comment {id : 3})<-[:RELATED_TO]-(:Comment {id : 4})

Querying:

MATCH p = (n:Comment)<-[RELATED_TO*]-(d:Comment)
// I believe you are interested only in the "complete" path.
// That is: you are not interested in the sub path like (:Comment {id : 2})-[:RELATED_TO]->(:Comment {id : 3}).
// So this WHERE clause is used to avoid these sub paths.
WHERE NOT (n)-->() AND NOT (d)<--()
CALL apoc.convert.toTree([p]) yield value
RETURN value

The output:

{
  "_type": "Comment",
  "related_to": [
    {
      "_type": "Comment",
      "related_to": [
        {
          "_type": "Comment",
          "related_to": [
            {
              "_type": "Comment",
              "_id": 142701,
              "id": 4
            }
          ],
          "_id": 142700,
          "id": 3
        }
      ],
      "_id": 142699,
      "id": 2
    }
  ],
  "_id": 142698,
  "id": 1
}

Alternatively you can return a list of nodes using the nodes() function passing the path as parameter:

MATCH p = (n:Comment)<-[RELATED_TO*]-(d:Comment)
WHERE NOT (n)-->() AND NOT (d)<--()
return nodes(p)

The result will be:

╒═════════════════════════════════════╕
│"nodes(p)"                           │
╞═════════════════════════════════════╡
│[{"id":1},{"id":2},{"id":3},{"id":4}]│
└─────────────────────────────────────┘

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM