无法在neo4j中的节点之间添加多个关系 [英] Cannot add more than one relationship between nodes in neo4j
问题描述
我正在尝试使用Neo4J建模社交网络.这要求一个用户可以与另一个用户具有多个关系.当我尝试保持这些关系时,只存储了一个.例如,这是我要做的测试单元:
I am trying to model a social network with Neo4J. This requires a user can have multiple relationships with another user. When I try to persist these relationships, only one is stored. For example, this is the test unit I do:
@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;
}
可能是什么问题?还有其他方法可以对节点之间的几种关系进行建模吗?
What could the problem be? Is there any other way to model several relationships between nodes?
推荐答案
这不是Neo4j的缺点,它是Spring Data Neo4j的限制.
This is not a shortcoming of Neo4j, it is a restriction of Spring Data Neo4j.
通常,如果您具有不同类型的关系,那么也应该实际选择不同的关系类型,而不要为此使用关系属性.
Usually if you have different types of relationships it would make sense to actually choose different relationship-types too, and not use a relationship-property for this.
CONNECTED_TO
也很通用.
Id
还是一个很普通的类,不是User
还是类似的东西?
Id
is also a pretty generic class, shouldn't that be User
or something similar?
FRIEND
COLLEAGUE
等会更有意义.
也就是说,如果您想保留自己的模型,则可以使用
That said, if you want to stay on your model you can either use
template.createRelationshipBetween(entity1,entity2,type,properties,true)
true
表示允许重复.
对于两种类型的关系,也可以使用两种不同的目标类型,并使用
Alternatively use two different target types for the 2 types of relationships and use
@RelatedTo(enforceTargetType=true)
这篇关于无法在neo4j中的节点之间添加多个关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!