Search code examples
pluginsneo4jneo4j-apoc

How to display relationships ids in the apoc.convert.toTree json result?


I'm using the apoc.convert.toTree procedure for my neo4j database. I would like to get the ids of the relationships like the nodes but I can't find how.

In the exemple, we can see that the id of the node is displayed :

{
         "_type":"Movie",
         "_id":33,
         "title":"Something's Gotta Give",
         "acted_in.roles":[
            "Julian Mercer"
         ]
}

But I would like to have also the id of the relationship :

{
         "_type":"Movie",
         "_id":33,
         "title":"Something's Gotta Give",
         "acted_in.roles":[
            "Julian Mercer"
         ]
         "acted_in._id": 65
}

I've tried to use the map config to get them :

CALL apoc.convert.toTree(paths, true, {
  rels:  {acted_in: ['_id']}
})

Unfortunately, It doesn't work. Do you have any suggestions ?


Solution

  • Unfortunately, that APOC function does not return the _id value of the relationship :ACTED_IN. Notice that the variable is a class variable which is preceded by _, so it implicitly added in the result.

    Try to experiment on the APOC and put a property in the relationship that doesn't exists like 'roleX':

    CALL apoc.convert.toTree(paths, true, {
      rels:  {acted_in: ['roleX']}
    })
    

    The result is none of the relationship properties (like roles), will be shown. It is because it cannot find a match on the list of properties in the relationship :ACTED_IN. The property _id is not an explicit property on :ACTED_IN so it does not work.

    I would suggest a hack so it is up to you if you like it. 1) create another property named: id which is the same value with id(rel) 2) then do your query such as {acted_in: ['id']}.

    Sample below:

    MATCH ()-[r:ACTED_IN]->() 
    SET r.id = id(r)
    

    then:

    CALL apoc.convert.toTree(paths, true, {
      rels:  {acted_in: ['id']}
    })
    

    Result:

    {
      "born": 1964,
      "_type": "Person",
      "name": "Keanu Reeves",
      "acted_in": [
        {
          "_type": "Movie",
          "_id": 154,
          "acted_in.id": 221,
          "title": "Something's Gotta Give",
          "released": 2003
        }
      ],
      "_id": 1
    }