gpt4 book ai didi

java - 在 java 类中创建 Neo4j Unique 节点

转载 作者:行者123 更新时间:2023-11-30 11:19:49 27 4
gpt4 key购买 nike

我想根据数据库中的列值创建节点和关系。Node1 值将来自“App-Name”列,Node2 -> “Corresponding_App” & relationship->“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);
}

它为每一行创建新节点。所以如何在上面的代码中创建唯一节点?

最佳答案

如果您的节点在名称方面是唯一的,您可以在简单的 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 缓存,然后确保按名称对您正在处理的结果进行排序。

关于java - 在 java 类中创建 Neo4j Unique 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23058700/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com