不能在neo4j中添加多个节点之间的关系
问题描述:
我想用Neo4J建模一个社交网络。这要求用户可以与另一个用户有多重关系。当我试图坚持这些关系时,只有一个存储。例如,这是测试单元我做的:不能在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的一个限制。
通常,如果您有不同类型的关系,则实际选择不同的关系类型也是有意义的,并且不要使用关系属性。
CONNECTED_TO
也很通用。
Id
也是一个非常通用的类,不应该是User
或类似的东西吗?
FRIEND
COLLEAGUE
等等会更有意义。
这就是说,如果你想留在你的模型,你可以使用
template.createRelationshipBetween(entity1,entity2,type,properties,true)
的true
代表让 - 重复。
或者使用两种不同的目标类型为2种类型的关系,并使用
@RelatedTo(enforceTargetType=true)
感谢您的信息!是的,这是非常通用的,这只是一个测试。我想用不同的类型来实现,问题是它们是在运行时定义的。我发现DynamicRelationshipEntity类,但不知道如何使用它,我找不到任何示例。你知道一个有效的例子吗? – 2013-02-21 23:23:39
使用枚举作为rel-types。否则'DynamicRelationshipType.withName(type)'。 – 2013-02-24 20:33:36