【问题标题】:Cannot add more than one relationship between nodes in neo4jNeo4j 中的节点之间不能添加多个关系
【发布时间】:2013-02-06 18:41:17
【问题描述】:

我正在尝试使用 Neo4J 为社交网络建模。这要求一个用户可以与另一个用户有多个关系。当我尝试保持这些关系时,只存储一个。例如,这是我做的测试单元:

@Test
public void testFindConnections() {

    Id id1 = new Id();
    id1.setId("first-node");

    Id id2 = new Id();
    id2.setId("second-node");
    idService.save(id2);

    id1.connectedTo(id2, "first-rel");
    id1.connectedTo(id2, "second-rel");

    idService.save(id1);

    for (Id im : idService.findAll()) {
        System.out.println("-" + im.getId());
        if (im.getConnections().size() > 0) {
            for (ConnectionType ite : im.getConnections()) {
                System.out
                        .println("--" + ite.getId() + " " + ite.getType());
            }
        }
    }
}

这应该输出:

-first-node
--0 first-rel
--1 second-rel
-second-node
--0 first-rel
--1 second-rel

但是,它输出:

-first-node
--0 first-rel
-second-node
--0 first-rel

这是我的节点实体:

@NodeEntity
public class Id {

    @GraphId
    Long nodeId;
    @Indexed(unique = false)
    String id;

    @Fetch
    @RelatedToVia(direction=Direction.BOTH)
    Collection<ConnectionType> connections = new HashSet<ConnectionType>();
}

还有我的关系实体:

@RelationshipEntity(type = "CONNECTED_TO")
public class ConnectionType {

    @GraphId Long id;
    @StartNode Id fromUser;
    @EndNode Id toUser;

    String type;
}

可能是什么问题?还有其他方法可以对节点之间的多个关系进行建模吗?

【问题讨论】:

    标签: neo4j spring-data-neo4j


    【解决方案1】:

    这不是 Neo4j 的缺点,是 Spring Data Neo4j 的限制。

    通常,如果您有不同类型的关系,那么实际上选择不同的关系类型也是有意义的,而不是为此使用关系属性。

    CONNECTED_TO 也很通用。

    Id 也是一个非常通用的类,不应该是User 或类似的吗?

    FRIENDCOLLEAGUE 等会更有意义。


    也就是说,如果你想继续使用你的模型,你可以使用

    template.createRelationshipBetween(entity1,entity2,type,properties,true)

    true 代表允许重复。

    为两种类型的关系交替使用两种不同的目标类型并使用

    @RelatedTo(enforceTargetType=true)

    【讨论】:

    • 感谢您的信息!是的,它非常通用,它只是一个测试。我想用不同的类型来做,问题是它们是在运行时定义的。我找到了 DynamicRelationshipEntity 类,但不确定如何使用它,我找不到任何示例。你知道一个可行的例子吗?
    • 使用枚举作为 rel 类型。否则DynamicRelationshipType.withName(type).
    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多