Given the following graph:
Definition:
Graph example :
-CompanyB holds 0.5 of companyC - CompanyA holds 0.5 companyB . Both companies are considered companyC's beneficiaries (each hold 0.5 directly and 0.25 indirectly respectively
Creating example:
// create an empty graph
graph = TinkerFactory.createModern()
g = graph.traversal()
g.V().drop()
// create data
companyA = g.addV('Company').property('name', 'A').next()
companyB= g.addV('Company').property('name', 'B').next()
companyC = g.addV('Company').property('name', 'C').next()
g.addE("Shareholder").from(companyB)
.to(companyC).property("holding",0.5)
g.addE("Shareholder").from(companyA)
.to(companyB).property("holding", 0.5)
Desired Solution:
Solution Example :
[{
name:"B",
holding:0.5,
shareholders:[
{
name:"A",
holding:0.25
}
]}
]
}]
My Attempt :
// js
let companyCBeneficiaries =await g.V(companyC.id)
.inE()
.project(
"holding",
"name",
"shareholders"
)
.by(__.identity().values("holding"))
.by(__.coalesce(__.outV().values("name") , __.constant("")))
.by(
__.coalesce(
__.outV().inE().project(
"name",
"holding"
)
.by(__.coalesce(__.outV().values("name") , __.constant("")))
.by(__.identity().values("holding"))
,
__.constant([])
)
)
.toList()
// console
g.V(companyC).inE().project("holding","name","shareholders")
.by(__.identity().values("holding"))
.by(__.coalesce(__.outV().values("name") ,__.constant("")))
.by(__.coalesce(__.outV().inE().project("name","holding")
.by(__.coalesce(__.outV().values("name") ,
__.constant("")))
.by(__.identity().values("holding"))
,__.constant([]))).toList()
Which result in CompanyA.holding = 0.5 instead of 0.25 (currently Im iterating over companyCBeneficiaries fixing the holding property )
I made your sample data bit more robust:
g = TinkerGraph.open().traversal()
companyA = g.addV('Company').property('name', 'A').next()
companyB = g.addV('Company').property('name', 'B').next()
companyC = g.addV('Company').property('name', 'C').next()
companyD = g.addV('Company').property('name', 'D').next()
companyE = g.addV('Company').property('name', 'E').next()
g.addE("Shareholder").from(companyB).to(companyC).property("holding",0.5)
g.addE("Shareholder").from(companyA).to(companyB).property("holding", 0.5)
g.addE("Shareholder").from(companyD).to(companyC).property("holding", 0.5)
g.addE("Shareholder").from(companyE).to(companyB).property("holding", 0.5)
and used sack()
which I think gets you what you are after:
gremlin> g.V().has('Company','name','C').
......1> inE('Shareholder').
......2> sack(assign).by('holding').
......3> project('name','holding','shareholders').
......4> by(outV().values('name')).
......5> by(sack()).
......6> by(outV().
......7> inE('Shareholder').
......8> sack(mult).by('holding').
......9> project('name','holding').
.....10> by(outV().values('name')).
.....11> by(sack()).
.....12> fold())
==>[name:B,holding:0.5,shareholders:[[name:A,holding:0.25],[name:E,holding:0.25]]]
==>[name:D,holding:0.5,shareholders:[]]