这是我提取树的解决方案:
注意:此解决方案适用于我的项目,但我必须针对您的问题对其进行更改,因为我们还有一些其他不必要的限制。
找到所有要提取的根实体后,
With entity as rootEntity
我已将这些匹配项添加到查询中:
match
rootEntity-[*0..]->subEntity,
parentEntity-->subEntity
这在哪里:
where rootEntity = subEntity or (rootEntity-[*0..]->parentEntity)
然后,我返回(不同)数据如下:
id(rootEntity),
id(parentEntity),
id(entity),
subEntity
其余的解决方案是 C#:
首先需要一些数据修复,因为 NEO4J 将多次返回根实体(每个传入关系一个):
results.ForEach(
x =>
{
if (x.Id == x.RootId)
x.ParentId = 0;
});
并按 ID 区分:
results =
results
.GroupBy(x => x.Id)
.Select(x => x.First())
.ToList();
然后,我们可以构建树:
....
var trees = results
.GroupBy(x => x.RootId)
.Select(singleTreeEntities => GenerateSingleEntity(singleTreeEntities.Key, singleTreeEntities))
return trees;
}
private Entity GenerateSingleEntity(long id, IEnumerable<Entities> treeEntities)
{
var currEntity = treeEntities.SingleOrDefault(x => x.Id == id);
return new Entity
{
Id = id,
SomeData = currEntity.SubEntity.SomeData,
SomeOtherData = currEntity.SubEntity.SomeOtherData,
ChildEntities =
treeEntities
.Where(x => x.ParentId == id)
.Select(x => GenerateSingleEntity(x.Id, treeEntities)))
};
}