Neo4j中双向关系的命名约定(使用Spring Data)

时间:2013-08-10 22:14:44

标签: neo4j spring-data-neo4j

我需要一些建议来给人际关系命名。另外,我不确定如何使用spring数据注释我的域实体。我见过的大多数例子都是单向的,选择的名称非常简单。

使用以下示例:

@NodeEntity
public class Person {   
    @Indexed
    private String name;

    @RelatedTo(type="OWNS", direction=Direction.OUTGOING)
    private Set<Car> cars;
} 

关系名称似乎没问题,没问题。

现在假设我想让这种关系成为双向的。以下方法有何不同(以及优点/缺点)。

1)使关系方向的两边= Direction.BOTH并调用关系类型=“OWNERSHIP”?

@NodeEntity
public class Person {   
    @Indexed
    private String name;

    @RelatedTo(type="OWNERSHIP", direction=Direction.BOTH)
    private Set<Car> cars;
}

@NodeEntity
public class Car {   
    @Indexed
    private String description;

    @RelatedTo(type="OWNERSHIP", direction=Direction.BOTH)
    private Person person;
}

2)两侧使用方向?

@NodeEntity
public class Person {   
    @Indexed
    private String name;

    @RelatedTo(type="OWNS", direction=Direction.OUTGOING)
    private Set<Car> cars;
}

@NodeEntity
public class Car {   
    @Indexed
    private String description;

    @RelatedTo(type="OWNED_BY", direction=Direction.INCOMING)
    private Person person;
}

1 个答案:

答案 0 :(得分:3)

Neo4j中没有双向关系。每个关系都有一个起始节点和一个结束节点。也就是说,您可以选择在编写遍历时忽略该方向,有效地将关系用作双向关系。

你想要建模的是拥有汽车的人。 (人) - [:OWNS] - &gt; (汽车)意味着两件事:从人的角度来看,这种外向的关系表明了拥有汽车的人。从汽车的角度来看,完全相同(但是传入)的关系意味着它归人所有。

如果没有指定方向,SDN中的@RelatedTo注释默认使用Direction.OUTGOING。这就是为什么你可能认为这些关系是双向的,但它们不是;它们默认为OUTGOING。

所以我会像这样建模您的域名:

@NodeEntity
public class Person {   
   @Indexed
   private String name;

   @RelatedTo(type="OWNS", direction=Direction.OUTGOING) //or no direction, same thing
   private Set<Car> cars;
}

@NodeEntity
public class Car {   
   @Indexed
   private String description;

   @RelatedTo(type="OWNS", direction=Direction.INCOMING)
   private Person person;
}
相关问题