Search code examples
c#graphneo4jneo4j-apoc

Need Neo4j Data Format json in c#


I'm trying to find the shortest path along with relations on the nodes on the path, for which below query is used.

MATCH p = shortestPath((p1:Person { name: 'Kevin Bacon' })-[*..15]- 
  (p2:Person { name: 'Meg Ryan' })) 
  UNWIND nodes(p) as n 
  MATCH (n)-[*]->(q) 
  RETURN n, q

However i want to return the result as json object with data format as below in c#. I understand we have to use apoc. However can't really understand how to proceed.

{
"results": [
    {    
        "data": [
            {
                "graph": {
                    "nodes": [
                        {
                            "id": "1",
                            "labels": ["James"],
                            "properties": {
                                "ShortName": "jammy",
                                "Type": "Person",
                                "Age": 34
                            }
                        },
                        {
                            "id": "2",
                            "labels": ["Brad"],
                            "properties": {
                                "name": "Brad",
                                "PlaceOfBirth": "California",
                                 "Type": "Person",
                                "description": "Nice actor",
                            }
                        },
                        {
                            "id": "3",
                            "labels": ["Titanic"],
                            "properties": {
                                "movieName": "Titanic", 
                                 "Type": "Movie",         
                                "description": "Tragedy",
                            }
                        }
                    ],
                    "relationships": [
                        {
                            "id": "4",
                            "type": "ACTED_IN",
                            "startNode": "1",
                            "endNode": "3",
                            "properties": {
                                "from": 1470002400000
                            }
                        }
                    ]
                }
            }
        ]
    }
],
"errors": []

}


Solution

  • You can collect the nodes and relationships separately and add it on the result.

    MATCH p = shortestPath((p1:Person { name: 'Kevin Bacon' })-[*..15]-(p2:Person { name: 'Meg Ryan' })) 
      UNWIND nodes(p) as n 
      MATCH (n)-[r]->(q) 
      WITH collect(distinct n) + collect(distinct q) as node_list, collect(distinct r) as rel_list
      RETURN {results: {data: {graph: {nodes: node_list, relationships: rel_list}}, error: []}} as output