我想根据DB中的列值创建节点和关系。 Node1值将来自列" App-Name",Node2-> " Corresponding_App" &安培;关系 - >" INTERFACE_NAME" 基于列值" Interface_Type_Name" - >传入/传出箭头将被绘制到特定节点。
节点应该是唯一的,如果已经创建,则不应创建重复节点。
Transaction tx=graphDb.beginTx();
Connection conn = null;
try{{
conn=ConnectionFactory.getConnection();
Statement stat=conn.createStatement();
String sql="select * from Fade where App_Int_Id < 22";
ResultSet rs=stat.executeQuery(sql);
String n1 = "",n2="",rel="",type="";
while(rs.next()){
n1=rs.getString(1);
n2=rs.getString(7);
rel=rs.getString(3);
type=rs.getString(4);
Node first=graphDb.createNode();
first.setProperty("name", n1);
first.addLabel(DynamicLabel.label(n1));
Node sec=graphDb.createNode();
sec.setProperty("name", n2);
sec.addLabel(DynamicLabel.label(n2));
RelationshipType KNOWS = DynamicRelationshipType.withName(rel);
if(type.equalsIgnoreCase("Incoming")){
sec.createRelationshipTo(first, KNOWS);
}
else if(type.equalsIgnoreCase("Outgoing")){
first.createRelationshipTo(sec, KNOWS);
}
对于每一行创建新节点。如何在上面的代码中创建唯一的节点?
答案 0 :(得分:1)
如果您的节点在名称方面是唯一的,您可以在简单的HashMap中跟踪它们以重用节点而不是创建新节点。这样的事情(警告,代码没有测试,但这应该给你的想法)。
HashMap<String,Node> nodes = new HashMap<String,Node>();
Transaction tx=graphDb.beginTx();
Connection conn = null;
try{{
conn=ConnectionFactory.getConnection();
Statement stat=conn.createStatement();
String sql="select * from Fade where App_Int_Id < 22";
ResultSet rs=stat.executeQuery(sql);
String n1 = "",n2="",rel="",type="";
while(rs.next()){
n1=rs.getString(1);
n2=rs.getString(7);
rel=rs.getString(3);
type=rs.getString(4);
Node first=nodes.get(n1);
// Only create it if it didn't already exist.
if(first == null) {
first = graphDb.createNode();
first.setProperty("name", n1);
first.addLabel(DynamicLabel.label(n1));
// Now put it in the map to ensure it doesn't get created again.
nodes.put(n1, first);
}
Node sec=nodes.get(n2);
if(sec == null) {
sec = graphDb.createNode();
sec.setProperty("name", n2);
sec.addLabel(DynamicLabel.label(n2));
// Now put it in the map to ensure it doesn't get created again.
nodes.put(n2, sec);
}
RelationshipType KNOWS = DynamicRelationshipType.withName(rel);
if(type.equalsIgnoreCase("Incoming")){
sec.createRelationshipTo(first, KNOWS);
}
else if(type.equalsIgnoreCase("Outgoing")){
first.createRelationshipTo(sec, KNOWS);
}
最后 - 如果您有大量节点,请不要尝试这样做,因为您的HashMap会超出内存。但至少应该可以使用几千个。如果您的数字非常庞大,请使用LRU缓存,然后确保您按照名称处理结果。