简体   繁体   English

如何查询neo4j的父节点实体中的子节点?

[英]How to query child nodes in parent node entity of neo4j?

For example, I have an entity like this: 例如,我有一个这样的实体:

@Data
@NodeEntity(label = "Subject")
public class Subject {
     @GraphId
     private Long id;
     private String name;

     @Relationship(type = "HAVE_S", direction = Relationship.OUTGOING)
     private Set<Subject> children = new HashSet<>();
}

Then I need to query a 'Subject' by graphId; 然后我需要通过graphId查询一个'Subject';

@Query("MATCH (s:Subject)-[r:HAVE_S*1]->(c:Subject) WHERE ID(s) = {graphId} RETURN s, r, c;")
Subject findById(@Param("graphId") Long graphId);

The result I want just like the following json: 我想要的结果就像以下json:

{
    "id": 62
    "name": "Java"
    "children": [
        {
            "name": "Collection",
            "id": 105
        },
        {
            "name": "MultipleThreads",
            "id": 0
        }
    ]
}

But when I executed the cypher above through Spring Data, an error comes out and says "Result not of expected size. Expected 1 row but found 3". 但是,当我通过Spring Data执行上述密码时,出现错误,并说“结果不是预期的大小。预期1行,但找到3行”。

I hope someone can help me with this problem, thanks. 我希望有人可以帮助我解决这个问题,谢谢。

As your model suggests A subject have multiple children so when you are fetching it by id it's returning a cartesian product of your subject* children. 正如您的模型所建议的那样,一个主题有多个孩子,因此当您通过id来获取它时,它将返回您的主题*孩子的笛卡尔积。 In this case you need to collect your children(subjects and then return) 在这种情况下,您需要收集孩子(对象然后返回)

@Query("MATCH (s:Subject)-[r:HAVE_S*1]->(c:Subject) WHERE ID(s) = {graphId} RETURN s,  collect(c) as childrens;")

or simply you can use findById() of your repository the SDN will create query by itself 或者您可以使用存储库中的findById()SDN将自行创建查询

You can try like this. 您可以这样尝试。

MATCH (k:LabelsTree {name:'465afe3c118589de357745a709c0441f'}) CALL apoc.path.spanningTree(k,{labelFilter:'+LabelsTree', maxLevel:3, optional:true, filterStartNode:true}) yield path return path

Refer to the connection 参考连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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