开源—neo4j的知识图谱

注意:开源作者为十点摆钟

Pair

在Apache Commons库中,org.apache.commons.lang3.tuple 包中提供Pair抽象类,它有两个子类,分别代表可变与不可变配对:ImmutablePair 和 MutablePair。两者都实现了访问key/value以及setter和getter方法。

 Pair<String, String> pair = Pair.of("aku", "female");
  pair.getLeft();
  pair.getRight();

这种Pair的返回对一个函数返回两个都有意义的值有特别用处。
总结:Pair的key是可以一样的,本质上 key 和 value 之间是没有任何区别的;

2.Neo4j的配置类

neo4j数据库的驱动

package com.modules.common.config;


import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * neo4j图数据库配置
 *
 * @author li'chao
 */

@Configuration
public class Neo4jConfig {
    @Value("${spring.data.neo4j.uri}")
    private String url;

    @Value("${spring.data.neo4j.username}")
    private String username;

    @Value("${spring.data.neo4j.password}")
    private String password;

    /**
     * neo4j图数据库驱动模式
     *
     * @return
     */
    @Bean
    public Driver neo4jDriver() {
        return GraphDatabase.driver(url, AuthTokens.basic(username, password));
    }
}

3.neo4j执行SQL

package com.modules.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.neo4j.driver.v1.*;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.neo4j.driver.v1.types.Relationship;
import org.neo4j.driver.v1.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;
import java.util.Map.Entry;

@Slf4j
@Component
public class Neo4jUtil {
  @Autowired
  private Driver neo4jDriver;

  public boolean isNeo4jOpen() {
  	try (Session session = neo4jDriver.session()) {
  		log.info("连接成功:" + session.isOpen());
  		return session.isOpen();
  	} catch (Exception e) {
  		log.error("连接异常:" + e.getMessage());
  		return false;
  	}
  }
  //1.执行sql得到数据result
  public StatementResult excuteCypherSql(String cypherSql) {
  	StatementResult result = null;
  	try (Session session = neo4jDriver.session()) {
  		log.info("cypher语句:" + cypherSql);
  		result = session.run(cypherSql);
  		session.close();
  	} catch (Exception e) {
  		throw e;
  	}
  	return result;
  }


  public HashMap<String, Object> getEntityMap(String cypherSql) {
  	HashMap<String, Object> rss = new HashMap<String, Object>();
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			List<Record> records = result.list();
  			for (Record recordItem : records) {
  				for (Value value : recordItem.values()) {
  					if (value.type().name().equals("NODE")) {// 结果里面只要类型为节点的值
  						Node noe4jNode = value.asNode();
  						Map<String, Object> map = noe4jNode.asMap();
  						for (Entry<String, Object> entry : map.entrySet()) {
  							String key = entry.getKey();
  							if (rss.containsKey(key)) {
  								String oldValue = rss.get(key).toString();
  								String newValue = oldValue + "," + entry.getValue();
  								rss.replace(key, newValue);
  							} else {
  								rss.put(key, entry.getValue());
  							}
  						}

  					}
  				}
  			}
  		}

  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return rss;
  }

  public List<HashMap<String, Object>> getGraphNode(String cypherSql) {
  	List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			List<Record> records = result.list();
  			for (Record recordItem : records) {
  				List<Pair<String, Value>> f = recordItem.fields();
  				for (Pair<String, Value> pair : f) {
  					HashMap<String, Object> rss = new HashMap<String, Object>();
  					String typeName = pair.value().type().name();
  					if (typeName.equals("NODE")) {
  						Node noe4jNode = pair.value().asNode();
  						String uuid = String.valueOf(noe4jNode.id());
  						Map<String, Object> map = noe4jNode.asMap();
  						for (Entry<String, Object> entry : map.entrySet()) {
  							String key = entry.getKey();
  							rss.put(key, entry.getValue());
  						}
  						rss.put("uuid", uuid);
  						ents.add(rss);
  					}
  				}

  			}
  		}

  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return ents;
  }
  //2.图谱关系
  public List<HashMap<String, Object>> getGraphRelationShip(String cypherSql) {
  	List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			List<Record> records = result.list();
  			for (Record recordItem : records) {
  				List<Pair<String, Value>> f = recordItem.fields();
  				for (Pair<String, Value> pair : f) {
  					HashMap<String, Object> rss = new HashMap<String, Object>();
  					String typeName = pair.value().type().name();
  					if (typeName.equals("RELATIONSHIP")) {
  						Relationship rship = pair.value().asRelationship();
  						String uuid = String.valueOf(rship.id());
  						String sourceid = String.valueOf(rship.startNodeId());
  						String targetid = String.valueOf(rship.endNodeId());
  						Map<String, Object> map = rship.asMap();
  						for (Entry<String, Object> entry : map.entrySet()) {
  							String key = entry.getKey();
  							rss.put(key, entry.getValue());
  						}
  						rss.put("uuid", uuid);
  						rss.put("sourceid", sourceid);
  						rss.put("targetid", targetid);
  						ents.add(rss);
  					}
  				}
  			}
  		}
  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return ents;
  }
  public List<HashMap<String, Object>> getGraphItem(String cypherSql) {
  	List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
  	List<String> nodeids = new ArrayList<String>();
  	List<String> shipids = new ArrayList<String>();
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			List<Record> records = result.list();
  			for (Record recordItem : records) {
  				List<Pair<String, Value>> f = recordItem.fields();
  				HashMap<String, Object> rss = new HashMap<String, Object>();
  				for (Pair<String, Value> pair : f) {
  					String typeName = pair.value().type().name();
  					if (typeName.equals("NODE")) {
  						Node noe4jNode = pair.value().asNode();
  						String uuid = String.valueOf(noe4jNode.id());
  						if(!nodeids.contains(uuid)) {
  							Map<String, Object> map = noe4jNode.asMap();
  							for (Entry<String, Object> entry : map.entrySet()) {
  								String key = entry.getKey();
  								rss.put(key, entry.getValue());
  							}
  							rss.put("uuid", uuid);
  						}
  					}else if (typeName.equals("RELATIONSHIP")) {
  						Relationship rship = pair.value().asRelationship();
  						String uuid = String.valueOf(rship.id());
  						if (!shipids.contains(uuid)) {
  							String sourceid = String.valueOf(rship.startNodeId());
  							String targetid = String.valueOf(rship.endNodeId());
  							Map<String, Object> map = rship.asMap();
  							for (Entry<String, Object> entry : map.entrySet()) {
  								String key = entry.getKey();
  								rss.put(key, entry.getValue());
  							}
  							rss.put("uuid", uuid);
  							rss.put("sourceid", sourceid);
  							rss.put("targetid", targetid);
  						}
  					}else {
  						rss.put(pair.key(),pair.value().toString());
  					}
  				}
  				ents.add(rss);
  			}
  		}
  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return ents;
  }
  /*
   * 获取值类型的结果,如count,uuid
   * @return 1 2 3 等数字类型
   */
  public long getGraphValue(String cypherSql) {
  	long val=0;
  	try {
  		StatementResult cypherResult = excuteCypherSql(cypherSql);
  		if (cypherResult.hasNext()) {
  			Record record = cypherResult.next();
  			for (Value value : record.values()) {
  				val = value.asLong();
  			}
  		}
  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return val;
  }

  public HashMap<String, Object> getGraphNodeAndShip(String cypherSql) {
  	HashMap<String, Object> mo = new HashMap<String, Object>();
  	try {
  		//1.得到所有的节点
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			List<Record> records = result.list();
  			List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
  			List<HashMap<String, Object>> ships = new ArrayList<HashMap<String, Object>>();
  			List<String> uuids = new ArrayList<String>();
  			List<String> shipids = new ArrayList<String>();
  			for (Record recordItem : records) {
  				List<Pair<String, Value>> f = recordItem.fields();
  				for (Pair<String, Value> pair : f) {
  					HashMap<String, Object> rships = new HashMap<String, Object>();
  					HashMap<String, Object> rss = new HashMap<String, Object>();
  					String typeName = pair.value().type().name();
  					if (typeName.equals("NULL")) {
  						continue;
  					} else if (typeName.equals("NODE")) {
  						Node noe4jNode = pair.value().asNode();
                          Map<String, Object> map = noe4jNode.asMap();
                          String uuid = String.valueOf(noe4jNode.id());
                          if (!uuids.contains(uuid)) {
                              for (Entry<String, Object> entry : map.entrySet()) {
                                  String key = entry.getKey();
                                  rss.put(key, entry.getValue());
                              }
                              rss.put("uuid", uuid);
                              uuids.add(uuid);
                          }
                          if (rss != null && !rss.isEmpty()) {
                              ents.add(rss);
                          }
  					} else if (typeName.equals("RELATIONSHIP")) {
  						Relationship rship = pair.value().asRelationship();
                          String uuid = String.valueOf(rship.id());
                          if (!shipids.contains(uuid)) {
                              String sourceid = String.valueOf(rship.startNodeId());
                              String targetid = String.valueOf(rship.endNodeId());
                              Map<String, Object> map = rship.asMap();
                              for (Entry<String, Object> entry : map.entrySet()) {
                                  String key = entry.getKey();
                                  rships.put(key, entry.getValue());
                              }
                              rships.put("uuid", uuid);
                              rships.put("sourceid", sourceid);
                              rships.put("targetid", targetid);
  							shipids.add(uuid);
                              if (rships != null && !rships.isEmpty()) {
                                  ships.add(rships);
                              }
                          }

  					} else if (typeName.equals("PATH")) {
  						Path path = pair.value().asPath();
  						Map<String, Object> startNodemap = path.start().asMap();
  						String startNodeuuid = String.valueOf(path.start().id());
  						if (!uuids.contains(startNodeuuid)) {
  							rss=new HashMap<String, Object>();
  							for (Entry<String, Object> entry : startNodemap.entrySet()) {
  								String key = entry.getKey();
  								rss.put(key, entry.getValue());
  							}
  							rss.put("uuid", startNodeuuid);
  							uuids.add(startNodeuuid);
  							if (rss != null && !rss.isEmpty()) {
  								ents.add(rss);
  							}
  						}

  						Map<String, Object> endNodemap = path.end().asMap();
  						String endNodeuuid = String.valueOf(path.end().id());
  						if (!uuids.contains(endNodeuuid)) {
  							rss=new HashMap<String, Object>();
  							for (Entry<String, Object> entry : endNodemap.entrySet()) {
  								String key = entry.getKey();
  								rss.put(key, entry.getValue());
  							}
  							rss.put("uuid", endNodeuuid);
  							uuids.add(endNodeuuid);
  							if (rss != null && !rss.isEmpty()) {
  								ents.add(rss);
  							}
  						}
  						Iterator<Node> allNodes = path.nodes().iterator();
  						while (allNodes.hasNext()) {
  							Node next = allNodes.next();
  							String uuid = String.valueOf(next.id());
  							if (!uuids.contains(uuid)) {
  								rss=new HashMap<String, Object>();
  								Map<String, Object> map = next.asMap();
  								for (Entry<String, Object> entry : map.entrySet()) {
  									String key = entry.getKey();
  									rss.put(key, entry.getValue());
  								}
  								rss.put("uuid", uuid);
  								uuids.add(uuid);
  								if (rss != null && !rss.isEmpty()) {
  									ents.add(rss);
  								}
  							}
  						}
  						Iterator<Relationship> reships = path.relationships().iterator();
  						while (reships.hasNext()) {
  							Relationship next = reships.next();
  							String uuid = String.valueOf(next.id());
  							if (!shipids.contains(uuid)) {
  								rships=new HashMap<String, Object>();
  								String sourceid = String.valueOf(next.startNodeId());
  								String targetid = String.valueOf(next.endNodeId());
  								Map<String, Object> map = next.asMap();
  								for (Entry<String, Object> entry : map.entrySet()) {
  									String key = entry.getKey();
  									rships.put(key, entry.getValue());
  								}
  								rships.put("uuid", uuid);
  								rships.put("sourceid", sourceid);
  								rships.put("targetid", targetid);
  								shipids.add(uuid);
  								if (rships != null && !rships.isEmpty()) {
  									ships.add(rships);
  								}
  							}
  						}
  					} else if (typeName.contains("LIST")) {
  						Iterable<Value> val=pair.value().values();
                          Value next = val.iterator().next();
                          String type=next.type().name();
                          if (type.equals("RELATIONSHIP")) {
                              Relationship rship = next.asRelationship();
                              String uuid = String.valueOf(rship.id());
                              if (!shipids.contains(uuid)) {
                                  String sourceid = String.valueOf(rship.startNodeId());
                                  String targetid = String.valueOf(rship.endNodeId());
                                  Map<String, Object> map = rship.asMap();
                                  for (Entry<String, Object> entry : map.entrySet()) {
                                      String key = entry.getKey();
                                      rships.put(key, entry.getValue());
                                  }
                                  rships.put("uuid", uuid);
                                  rships.put("sourceid", sourceid);
                                  rships.put("targetid", targetid);
  								shipids.add(uuid);
                                  if (rships != null && !rships.isEmpty()) {
                                      ships.add(rships);
                                  }
                              }
                          }
  					} else if (typeName.contains("MAP")) {
  						rss.put(pair.key(), pair.value().asMap());
  					} else {
  						rss.put(pair.key(), pair.value().toString());
                          if (rss != null && !rss.isEmpty()) {
                              ents.add(rss);
                          }
  					}
  				}
  			}
  			mo.put("node", ents);
  			mo.put("relationship", ships);
  		}
  	} catch (Exception e) {
  		throw new RuntimeException("执行Cypher查询异常");
  	}
  	return mo;
  }
  /**
   * 匹配所有类型的节点,可以是节点,关系,数值,路径
   * @param cypherSql
   * @return
   */
  public List<HashMap<String, Object>> getEntityList(String cypherSql) {
  	List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			List<Record> records = result.list();
  			for (Record recordItem : records) {
  				HashMap<String, Object> rss = new HashMap<String, Object>();
  				List<Pair<String, Value>> f = recordItem.fields();
  				for (Pair<String, Value> pair : f) {
  					String typeName = pair.value().type().name();
  					if (typeName.equals("NULL")) {
  						continue;
  					} else if (typeName.equals("NODE")) {
  						Node noe4jNode = pair.value().asNode();
  						Map<String, Object> map = noe4jNode.asMap();
  						for (Entry<String, Object> entry : map.entrySet()) {
  							String key = entry.getKey();
  							rss.put(key, entry.getValue());
  						}
  					} else if (typeName.equals("RELATIONSHIP")) {
  						Relationship rship = pair.value().asRelationship();
  						Map<String, Object> map = rship.asMap();
  						for (Entry<String, Object> entry : map.entrySet()) {
  							String key = entry.getKey();
  							rss.put(key, entry.getValue());
  						}
  					} else if (typeName.equals("PATH")) {

  					} else if (typeName.contains("LIST")) {
  						rss.put(pair.key(), pair.value().asList());
  					} else if (typeName.contains("MAP")) {
  						rss.put(pair.key(), pair.value().asMap());
  					} else {
  						rss.put(pair.key(), pair.value().toString());
  					}
  				}
  				ents.add(rss);
  			}
  		}

  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return ents;
  }

  public <T> List<T> getEntityItemList(String cypherSql, Class<T> type) {
  	List<HashMap<String, Object>> ents = getGraphNode(cypherSql);
  	List<T> model = hashMapToObject(ents, type);
  	return model;
  }

  public <T> T getEntityItem(String cypherSql, Class<T> type) {
  	HashMap<String, Object> rss = new HashMap<String, Object>();
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			Record record = result.next();
  			for (Value value : record.values()) {
  				if (value.type().name().equals("NODE")) {// 结果里面只要类型为节点的值
  					Node noe4jNode = value.asNode();
  					Map<String, Object> map = noe4jNode.asMap();
  					for (Entry<String, Object> entry : map.entrySet()) {
  						String key = entry.getKey();
  						if (rss.containsKey(key)) {
  							String oldValue = rss.get(key).toString();
  							String newValue = oldValue + "," + entry.getValue();
  							rss.replace(key, newValue);
  						} else {
  							rss.put(key, entry.getValue());
  						}
  					}

  				}
  			}
  		}

  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	T model = hashMapToObjectItem(rss, type);
  	return model;
  }

  public HashMap<String, Object> getEntity(String cypherSql) {
  	HashMap<String, Object> rss = new HashMap<String, Object>();
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			Record record = result.next();
  			for (Value value : record.values()) {
  				String t = value.type().name();
  				if (value.type().name().equals("NODE")) {// 结果里面只要类型为节点的值
  					Node noe4jNode = value.asNode();
  					Map<String, Object> map = noe4jNode.asMap();
  					for (Entry<String, Object> entry : map.entrySet()) {
  						String key = entry.getKey();
  						if (rss.containsKey(key)) {
  							String oldValue = rss.get(key).toString();
  							String newValue = oldValue + "," + entry.getValue();
  							rss.replace(key, newValue);
  						} else {
  							rss.put(key, entry.getValue());
  						}
  					}

  				}
  			}
  		}

  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return rss;
  }

  public Integer executeScalar(String cypherSql) {
  	Integer count = 0;
  	try {
  		StatementResult result = excuteCypherSql(cypherSql);
  		if (result.hasNext()) {
  			Record record = result.next();
  			for (Value value : record.values()) {
  				String t = value.type().name();
  				if (t.equals("INTEGER")) {
  					count = Integer.valueOf(value.toString());
  					break;
  				}
  			}
  		}

  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return count;
  }

  public HashMap<String, Object> getRelevantEntity(String cypherSql) {
  	HashMap<String, Object> rss = new HashMap<String, Object>();
  	try {
  		StatementResult resultNode = excuteCypherSql(cypherSql);
  		if (resultNode.hasNext()) {
  			List<Record> records = resultNode.list();
  			for (Record recordItem : records) {
  				Map<String, Object> r = recordItem.asMap();
  				String key = r.get("key").toString();
  				if (rss.containsKey(key)) {
  					String oldValue = rss.get(key).toString();
  					String newValue = oldValue + "," + r.get("value");
  					rss.replace(key, newValue);
  				} else {
  					rss.put(key, r.get("value"));
  				}
  			}
  		}
  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return rss;
  }



  public String getFilterPropertiesJson(String jsonStr) {
  	String propertiesString = jsonStr.replaceAll("\"(\\w+)\"(\\s*:\\s*)", "$1$2"); // 去掉key的引号
  	return propertiesString;
  }

  public <T>String getkeyvalCyphersql(T obj) {
  	 Map<String, Object> map = new HashMap<String, Object>();
  	 List<String> sqlList=new ArrayList<String>();
          // 得到类对象
          Class userCla = obj.getClass();
          /* 得到类中的所有属性集合 */
          Field[] fs = userCla.getDeclaredFields();
          for (int i = 0; i < fs.length; i++) {
              Field f = fs[i];
              Class type = f.getType();

              f.setAccessible(true); // 设置些属性是可以访问的
              Object val = new Object();
              try {
                  val = f.get(obj);
                  if(val==null) {
                  	val="";
                  }
                  String sql="";
                  String key=f.getName();
                  log.info("key:"+key+"type:"+type);
                  if ( val instanceof   Integer ){
                  	// 得到此属性的值
  	                map.put(key, val);// 设置键值
  	                sql="n."+key+"="+val;
      			}
                  else if ( val instanceof   String[] ){
      				//如果为true则强转成String数组
      				String [] arr = ( String[] ) val ;
      				String v="";
      				for ( int j = 0 ; j < arr.length ; j++ ){
      					arr[j]="'"+ arr[j]+"'";
      				}
      				v=String.join(",", arr);
      				sql="n."+key+"=["+val+"]";
      			}
                  else if (val instanceof List){
      				//如果为true则强转成String数组
                  	List<String> arr = ( ArrayList<String> ) val ;
                  	List<String> aa=new ArrayList<String>();
      				String v="";
      				for (String s : arr) {
      					s="'"+ s+"'";
      					aa.add(s);
  					}
      				v=String.join(",", aa);
      				sql="n."+key+"=["+v+"]";
      			}
                  else {
                  	// 得到此属性的值
  	                map.put(key, val);// 设置键值
  	                sql="n."+key+"='"+val+"'";
                  }

                  sqlList.add(sql);
              } catch (IllegalArgumentException e) {
                  e.printStackTrace();
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
              }
          }
          String finasql=String.join(",",sqlList);
          log.info("单个对象的所有键值==反射==" + map.toString());
  	return finasql;
  }
  public <T> List<T> hashMapToObject(List<HashMap<String, Object>> maps, Class<T> type) {
  	try {
  		List<T> list = new ArrayList<T>();
  		for (HashMap<String, Object> r : maps) {
  			T t = type.newInstance();
  			Iterator iter = r.entrySet().iterator();// 该方法获取列名.获取一系列字段名称.例如name,age...
  			while (iter.hasNext()) {
  				Entry entry = (Entry) iter.next();// 把hashmap转成Iterator再迭代到entry
  				String key = entry.getKey().toString(); // 从iterator遍历获取key
  				Object value = entry.getValue(); // 从hashmap遍历获取value
  				if("serialVersionUID".toLowerCase().equals(key.toLowerCase()))continue;
  				Field field = type.getDeclaredField(key);// 获取field对象
  				if (field != null) {
  					field.setAccessible(true);
  					if (field.getType() == int.class || field.getType() == Integer.class) {
  						if (value==null||StringUtils.isBlank(value.toString())) {
  							field.set(t, 0);// 设置值
  						} else {
  							field.set(t, Integer.parseInt(value.toString()));// 设置值
  						}
  					}
  					 else if (field.getType() == long.class||field.getType() == Long.class ) {
  							if (value==null||StringUtils.isBlank(value.toString())) {
  								field.set(t, 0);// 设置值
  							} else {
  								field.set(t, Long.parseLong(value.toString()));// 设置值
  							}

  					}
  					 else {
  						field.set(t, value);// 设置值
  					}
  				}

  			}
  			list.add(t);
  		}

  		return list;
  	} catch (Exception e) {
  		throw new RuntimeException(e);
  	}
  }

  public <T> T hashMapToObjectItem(HashMap<String, Object> map, Class<T> type) {
  	try {
  		T t = type.newInstance();
  		Iterator iter = map.entrySet().iterator();
  		while (iter.hasNext()) {
  			Entry entry = (Entry) iter.next();// 把hashmap转成Iterator再迭代到entry
  			String key = entry.getKey().toString(); // 从iterator遍历获取key
  			Object value = entry.getValue(); // 从hashmap遍历获取value
  			if("serialVersionUID".toLowerCase().equals(key.toLowerCase()))continue;
  			Field field = type.getDeclaredField(key);// 获取field对象
  			if (field != null) {
  				field.setAccessible(true);
  				if (field.getType() == int.class || field.getType() == Integer.class) {
  					if (value==null||StringUtils.isBlank(value.toString())) {
  						field.set(t, 0);// 设置值
  					} else {
  						field.set(t, Integer.parseInt(value.toString()));// 设置值
  					}
  				}
  				 else if (field.getType() == long.class||field.getType() == Long.class ) {
  						if (value==null||StringUtils.isBlank(value.toString())) {
  							field.set(t, 0);// 设置值
  						} else {
  							field.set(t, Long.parseLong(value.toString()));// 设置值
  						}

  				}
  				 else {
  					field.set(t, value);// 设置值
  				}
  			}

  		}
  		return t;
  	} catch (Exception e) {
  		throw new RuntimeException(e);
  	}
  }

  public List<String> getNodesLabelsEntityList(String cypherSql) {
  	List<String> rss = new ArrayList<>();
  	try {
  		StatementResult resultNode = excuteCypherSql(cypherSql);
  		if (resultNode.hasNext()) {
  			List<Record> records = resultNode.list();
  			for (Record recordItem : records) {
  				Map<String, Object> r = recordItem.asMap();
  				rss.add(r.get("label").toString());
  			}
  		}
  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return rss;
  }

  public List<String> getRelationshipTypeEntityList(String cypherSql) {
  	List<String> rss = new ArrayList<>();
  	try {
  		StatementResult resultNode = excuteCypherSql(cypherSql);
  		if (resultNode.hasNext()) {
  			List<Record> records = resultNode.list();
  			for (Record recordItem : records) {
  				Map<String, Object> r = recordItem.asMap();
  				rss.add(r.get("relationshipType").toString());
  			}
  		}
  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return rss;
  }
}

3.控制层

Neo4j数据的管理

package com.modules.project.controller;

import com.modules.common.utils.Neo4jUtil;
import com.modules.common.web.BaseController;
import com.modules.common.web.Result;
import com.modules.project.entity.GraphQuery;
import com.modules.project.service.GraphService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * neo4j图数据管理
 *
 * @author li'chao
 */

@Api(tags = "neo4j图数据管理")
@Slf4j
@RestController
@RequestMapping("/graph")
public class GraphController extends BaseController {

    @Autowired
    private Neo4jUtil neo4jUtil;

    @Autowired
    private GraphService graphService;

    @ApiOperation(value = "执行Cypher查询", notes = "执行Cypher查询")
    @GetMapping(value = "/getCypherResult")
    public Result getCypherResult(String cypher) {
        try {
            HashMap<String, Object> graphData = neo4jUtil.getGraphNodeAndShip(cypher);
            return success(graphData);
        } catch (Exception e) {
            log.error("执行Cypher查询异常:" + e.getMessage());
           return error("执行Cypher查询异常");
        }
    }

    @ApiOperation(value = "查询图节点和关系", notes = "查询图节点和关系")
    @GetMapping(value = "/getDomainGraph")
    public Result getDomainGraph(@Validated GraphQuery query) {
        try {
            HashMap<String, Object> graphData = graphService.getDomainGraph(query);
            return success(graphData);
        } catch (Exception e) {
            log.error("查询图节点和关系异常:" + e.getMessage());
           return error("查询图节点和关系异常");
        }
    }

    @ApiOperation(value = "获取节点列表", notes = "获取节点列表")
    @GetMapping(value = "/getDomainNodes")
    public Result getDomainNodes(String domain, Integer pageIndex, Integer pageSize) {
        try {
            HashMap<String, Object> graphData = graphService.getDomainNodes(domain, pageIndex,pageSize);
            return success(graphData);
        } catch (Exception e) {
            log.error("获取节点列表异常:" + e.getMessage());
            return error("获取节点列表异常");
        }
    }

    @ApiOperation(value = "查询所有节点标签", notes = "查询所有的节点标签")
    @GetMapping(value = "/getNodesLabels")
    public Result getNodesLabels() {
        try {
            List<String> graphData = graphService.getNodesLabels();
            return success(graphData);
        } catch (Exception e) {
            log.error("查询所有节点标签异常:" + e.getMessage());
            return error("查询所有节点标签异常");
        }
    }

    @ApiOperation(value = "查询所有关系类型", notes = "查询所有关系类型")
    @GetMapping(value = "/getRelationshipType")
    public Result getRelationshipType() {
        try {
            List<String> graphData = graphService.getRelationshipType();
            return success(graphData);
        } catch (Exception e) {
            log.error("查询所有关系类型异常:" + e.getMessage());
            return error("查询所有关系类型异常");
        }
    }
}

4.业务类

package com.modules.project.service;

import com.modules.common.utils.StringUtils;
import com.modules.project.entity.GraphQuery;
import com.modules.project.repository.GraphRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * neo4j图库服务层
 *
 * @author li'chao
 *
 */

@Service
public class GraphService {

    @Autowired
    private GraphRepository graphRepository;

    /**
     * 查询图节点和关系
     *
     * @param query
     * @return
     */
    public HashMap<String, Object> getDomainGraph(GraphQuery query) {
        if(StringUtils.isNotEmpty(query.getDomain())){
            return graphRepository.getDomainGraph(query);
        }else{
            return graphRepository.getNodeNameGraph(query);
        }
    }

    /**
     * 获取节点列表
     * @param domain
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public HashMap<String, Object> getDomainNodes(String domain, Integer pageIndex, Integer pageSize){
        return graphRepository.getDomainNodes(domain, pageIndex, pageSize);
    }

    /**
     * 查询所有节点标签
     * @return
     */
    public List<String> getNodesLabels(){
        return graphRepository.getNodesLabels();
    }

    /**
     * 查询所有关系类型
     * @return
     */
    public List<String> getRelationshipType(){
        return graphRepository.getRelationshipType();
    }
}

5.接口层

package com.modules.project.repository;

import com.modules.project.entity.GraphPageRecord;
import com.modules.project.entity.GraphQuery;
import com.modules.project.entity.QAEntityItem;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public interface GraphRepository {
	/**
	 * 领域标签分页
	 * @param queryItem
	 * @return
	 */
	GraphPageRecord<HashMap<String, Object>> getPageDomain(GraphQuery queryItem);
	/**
	 * 删除Neo4j 标签
	 *
	 * @param domain
	 */
	void deleteKGdomain(String domain);

	/**
	 * 查询图谱节点和关系
	 *
	 * @param query
	 * @return node relationship
	 */
	HashMap<String, Object> getDomainGraph(GraphQuery query);

	/**
	 * 查询图谱节点和关系(条件无节点标签)
	 *
	 * @param query
	 * @return node relationship
	 */
	HashMap<String, Object> getNodeNameGraph(GraphQuery query);

	/**
	 * 获取节点列表
	 *
	 * @param domain
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	HashMap<String, Object> getDomainNodes(String domain, Integer pageIndex, Integer pageSize);

	/**
	 * 获取某个领域指定节点拥有的上下级的节点数
	 *
	 * @param domain
	 * @param nodeid
	 * @return long 数值
	 */
	long getRelationNodeCount(String domain, long nodeid);

	/**
	 * 创建领域,默认创建一个新的节点,给节点附上默认属性
	 *
	 * @param domain
	 */
	void createDomain(String domain);

	/**
	 * 获取/展开更多节点,找到和该节点有关系的节点
	 *
	 * @param domain
	 * @param nodeid
	 * @return
	 */
	HashMap<String, Object> getMorerelationNode(String domain, String nodeid);

	/**
	 * 更新节点名称
	 *
	 * @param domain
	 * @param nodeid
	 * @param nodename
	 * @return 修改后的节点
	 */
	HashMap<String, Object> updateNodeName(String domain, String nodeid, String nodename);

	/**
	 * 创建单个节点
	 *
	 * @param domain
	 * @param entity
	 * @return
	 */
	HashMap<String, Object> createNode(String domain, QAEntityItem entity);

	/**
	 * 批量创建节点和关系
	 *
	 * @param domain
	 *            领域
	 * @param sourcename
	 *            源节点
	 * @param relation
	 *            关系
	 * @param targetnames
	 *            目标节点数组
	 * @return
	 */
	HashMap<String, Object> batchCreateNode(String domain, String sourcename, String relation, String[] targetnames);

	/**
	 * 批量创建下级节点
	 *
	 * @param domain
	 *            领域
	 * @param sourceid
	 *            源节点id
	 * @param entitytype
	 *            节点类型
	 * @param targetnames
	 *            目标节点名称数组
	 * @param relation
	 *            关系
	 * @return
	 */
	HashMap<String, Object> batchCreateChildCode(String domain, String sourceid, Integer entitytype,
			String[] targetnames, String relation);

	/**
	 * 批量创建同级节点
	 *
	 * @param domain
	 *            领域
	 * @param entitytype
	 *            节点类型
	 * @param sourcenames
	 *            节点名称
	 * @return
	 */
	List<HashMap<String, Object>> batchCreateSameCode(String domain, Integer entitytype, String[] sourcenames);

	/**
	 * 添加关系
	 *
	 * @param domain
	 *            领域
	 * @param sourceid
	 *            源节点id
	 * @param targetid
	 *            目标节点id
	 * @param ship
	 *            关系
	 * @return
	 */
	HashMap<String, Object> createLink(String domain, long sourceid, long targetid, String ship);

	/**
	 * 更新关系
	 *
	 * @param domain
	 *            领域
	 * @param shipid
	 *            关系id
	 * @param shipname
	 *            关系名称
	 * @return
	 */
	HashMap<String, Object> updateLink(String domain, long shipid, String shipname);

	/**
	 * 删除节点(先删除关系再删除节点)
	 *
	 * @param domain
	 * @param nodeid
	 * @return
	 */
	List<HashMap<String, Object>> deleteNode(String domain, long nodeid);

	/**
	 * 删除关系
	 *
	 * @param domain
	 * @param shipid
	 */
	void deleteLink(String domain, long shipid);

	/**
	 * 段落识别出的三元组生成图谱
	 *
	 * @param domain
	 * @param entitytype
	 * @param operatetype
	 * @param sourceid
	 * @param rss
	 *            关系三元组
	 *            [[startname;ship;endname],[startname1;ship1;endname1],[startname2;ship2;endname2]]
	 * @return node relationship
	 */
	HashMap<String, Object> createGraphByText(String domain, Integer entitytype, Integer operatetype, Integer sourceid,
			String[] rss);
	/**
	 * 批量创建节点,关系
	 * @param domain
	 * @param params 三元组 sourcenode,relationship,targetnode
	 */
	void batchCreateGraph(String domain, List<Map<String,Object>> params);
	/**
	 * 更新节点有无附件
	 * @param domain
	 * @param nodeId
	 * @param status
	 */
	void updateNodeFileStatus(String domain,long nodeId, int status);
	/**
	 * 导入csv
	 * @param domain
	 * @param csvUrl
	 * @param status
	 */
	void batchInsertByCSV(String domain, String csvUrl, int status) ;

	void updateCorrdOfNode(String domain, String uuid, Double fx, Double fy);

	/**
	 * 查询所有节点标签
	 * @return
	 */
	List<String> getNodesLabels();

	/**
	 * 查询所有关系类型
	 * @return
	 */
	public List<String> getRelationshipType();

	/**
	 * 查询节点关系种类
	 * @return
	 */
	public List<String> getNodesSchema();
}
接口实现类

本质:业务类传参数给到底层的接口类,进行替换到底层的SQL中,Neo4j工具类进行执行

package com.modules.project.repository.impl;

import com.alibaba.fastjson.JSON;
import com.modules.common.utils.Neo4jUtil;
import com.modules.common.utils.StringUtils;
import com.modules.project.entity.GraphPageRecord;
import com.modules.project.entity.GraphQuery;
import com.modules.project.entity.QAEntityItem;
import com.modules.project.repository.GraphRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * neo4j图库 Repository
 *
 * @author li'chao
 *
 */
@Repository
public class GraphImplRepository implements GraphRepository {
	@Autowired
	private Neo4jUtil neo4jUtil;

	/**
	 * 领域标签分页
	 *
	 * @param queryItem
	 * @return
	 */
	public GraphPageRecord<HashMap<String, Object>> getPageDomain(GraphQuery queryItem) {
		GraphPageRecord<HashMap<String, Object>> resultRecord = new GraphPageRecord<HashMap<String, Object>>();
		try {
			String totalCountquery = "MATCH (n) RETURN count(distinct labels(n)) as count";
			int totalCount = 0;
			totalCount = neo4jUtil.executeScalar(totalCountquery);
			if (totalCount > 0) {
				int skipCount = (queryItem.getPageIndex() - 1) * queryItem.getPageSize();
				int limitCount = queryItem.getPageSize();
				String domainSql = String.format(
						"START n=node(*)  RETURN distinct labels(n) as domain,count(n) as nodecount order by nodecount desc SKIP %s LIMIT %s",
						skipCount, limitCount);
				List<HashMap<String, Object>> pageList = neo4jUtil.getEntityList(domainSql);
				resultRecord.setPageIndex(queryItem.getPageIndex());
				resultRecord.setPageSize(queryItem.getPageSize());
				resultRecord.setTotalCount(totalCount);
				resultRecord.setNodeList(pageList);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultRecord;
	}

	/**
	 * 删除Neo4j 标签
	 *
	 * @param domain
	 */
	public void deleteKGdomain(String domain) {
		try {
			String rSql = String.format("MATCH (n:`%s`) -[r]-(m)  delete r", domain);
			neo4jUtil.excuteCypherSql(rSql);
			String deleteNodeSql = String.format("MATCH (n:`%s`) delete n", domain);
			neo4jUtil.excuteCypherSql(deleteNodeSql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询图谱节点和关系
	 *
	 * @param query
	 * @return node relationship
	 */
	public HashMap<String, Object> getDomainGraph(GraphQuery query) {
		HashMap<String, Object> nr = new HashMap<String, Object>();
		try {
			String domain = query.getDomain();
			// MATCH (n:`症状`) -[r]-(m:症状) where r.name='治疗' or r.name='危险因素' return n,m
			if (!StringUtils.isBlank(domain)) {
				String cqr = "";
				List<String> lis = new ArrayList<String>();
				if (query.getRelation() != null && query.getRelation().length > 0) {
					for (String r : query.getRelation()) {
						String it = String.format("r.name='%s'", r);
						lis.add(it);
					}
					cqr = String.join(" or ", lis);
				}
				String cqWhere = "";
				if (!StringUtils.isBlank(query.getNodename()) || !StringUtils.isBlank(cqr)) {

					if (!StringUtils.isBlank(query.getNodename())) {
						if (query.getMatchtype() == 1) {
							cqWhere = String.format("where n.name ='%s' ", query.getNodename());

						} else {
							cqWhere = String.format("where n.name contains('%s')", query.getNodename());
						}
					}
					String nodeOnly = cqWhere;
					if (!StringUtils.isBlank(cqr)) {
						if (StringUtils.isBlank(cqWhere)) {
							cqWhere = String.format(" where ( %s )", cqr);

						} else {
							cqWhere += String.format(" and ( %s )", cqr);
						}

					}
					// 下边的查询查不到单个没有关系的节点,考虑要不要左箭头
					String nodeSql = String.format("MATCH (n:`%s`) <-[r]->(m) %s return * limit %s", domain, cqWhere,
							query.getPageSize());
					HashMap<String, Object> graphNode = neo4jUtil.getGraphNodeAndShip(nodeSql);
					Object node = graphNode.get("node");
					// 没有关系显示则显示节点
					if (node != null) {
						nr.put("node", graphNode.get("node"));
						nr.put("relationship", graphNode.get("relationship"));
					} else {
						String nodecql = String.format("MATCH (n:`%s`) %s RETURN distinct(n) limit %s", domain,
								nodeOnly, query.getPageSize());
						List<HashMap<String, Object>> nodeItem = neo4jUtil.getGraphNode(nodecql);
						nr.put("node", nodeItem);
						nr.put("relationship", new ArrayList<HashMap<String, Object>>());
					}
				} else {
					String nodeSql = String.format("MATCH (n:`%s`) %s RETURN distinct(n) limit %s", domain, cqWhere,
							query.getPageSize());
					List<HashMap<String, Object>> graphNode = neo4jUtil.getGraphNode(nodeSql);
					nr.put("node", graphNode);
					String domainSql = String.format("MATCH (n:`%s`)<-[r]-> (m) %s RETURN distinct(r) limit %s", domain,
							cqWhere, query.getPageSize());// m是否加领域
					List<HashMap<String, Object>> graphRelation = neo4jUtil.getGraphRelationShip(domainSql);
					nr.put("relationship", graphRelation);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nr;
	}

	/**
	 * 查询图谱节点和关系(条件无节点标签)
	 *
	 * @param query
	 * @return node relationship
	 */
	public HashMap<String, Object> getNodeNameGraph(GraphQuery query) {
		HashMap<String, Object> nr = new HashMap<String, Object>();
		try {
			// MATCH (n) -[r]-(m:症状) where r.name='治疗' or r.name='危险因素' return n,m
			String cqr = "";
			List<String> lis = new ArrayList<String>();
			if (query.getRelation() != null && query.getRelation().length > 0) {
				for (String r : query.getRelation()) {
					String it = String.format("r.name='%s'", r);
					lis.add(it);
				}
				cqr = String.join(" or ", lis);
			}
			String cqWhere = "";
			if (!StringUtils.isBlank(query.getNodename()) || !StringUtils.isBlank(cqr)) {

				if (!StringUtils.isBlank(query.getNodename())) {
					if (query.getMatchtype() == 1) {
						cqWhere = String.format("where n.name ='%s' ", query.getNodename());

					} else {
						cqWhere = String.format("where n.name contains('%s')", query.getNodename());
					}
				}
				String nodeOnly = cqWhere;
				if (!StringUtils.isBlank(cqr)) {
					if (StringUtils.isBlank(cqWhere)) {
						cqWhere = String.format(" where ( %s )", cqr);

					} else {
						cqWhere += String.format(" and ( %s )", cqr);
					}
				}
				// 下边的查询查不到单个没有关系的节点,考虑要不要左箭头
				String nodeSql = String.format("MATCH (n) <-[r]->(m) %s return * limit %s", cqWhere,
						query.getPageSize());
				HashMap<String, Object> graphNode = neo4jUtil.getGraphNodeAndShip(nodeSql);
				Object node = graphNode.get("node");
				// 没有关系显示则显示节点
				if (node != null) {
					nr.put("node", graphNode.get("node"));
					nr.put("relationship", graphNode.get("relationship"));
				} else {
					String nodecql = String.format("MATCH (n) %s RETURN distinct(n) limit %s",
							nodeOnly, query.getPageSize());
					List<HashMap<String, Object>> nodeItem = neo4jUtil.getGraphNode(nodecql);
					nr.put("node", nodeItem);
					nr.put("relationship", new ArrayList<HashMap<String, Object>>());
				}
			} else {
				String nodeSql = String.format("MATCH (n) %s RETURN distinct(n) limit %s", cqWhere,
						query.getPageSize());
				List<HashMap<String, Object>> graphNode = neo4jUtil.getGraphNode(nodeSql);
				nr.put("node", graphNode);
				String domainSql = String.format("MATCH (n)<-[r]-> (m) %s RETURN distinct(r) limit %s",
						cqWhere, query.getPageSize());// m是否加领域
				List<HashMap<String, Object>> graphRelation = neo4jUtil.getGraphRelationShip(domainSql);
				nr.put("relationship", graphRelation);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nr;
	}

	/**
	 * 获取节点列表
	 *
	 * @param domain
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	public HashMap<String, Object> getDomainNodes(String domain, Integer pageIndex, Integer pageSize) {
		HashMap<String, Object> resultItem = new HashMap<String, Object>();
		List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> concepts = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> props = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> methods = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> entitys = new ArrayList<HashMap<String, Object>>();
		try {
			int skipCount = (pageIndex - 1) * pageSize;
			int limitCount = pageSize;
			String domainSql = String.format("START n=node(*) MATCH (n:`%s`) RETURN n SKIP %s LIMIT %s", domain,
					skipCount, limitCount);
			if (!StringUtils.isBlank(domain)) {
				ents = neo4jUtil.getGraphNode(domainSql);
				for (HashMap<String, Object> hashMap : ents) {
					Object et = hashMap.get("entitytype");
					if (et != null) {
						String typeStr = et.toString();
						if (StringUtils.isNotBlank(typeStr)) {
							int type = Integer.parseInt(et.toString());
							if (type == 0) {
								concepts.add(hashMap);
							} else if (type == 1) {
								entitys.add(hashMap);
							} else if (type == 2 || type == 3) {
								props.add(hashMap);// 属性和方法放在一起展示
							} else {
								// methods.add(hashMap);
							}
						}
					}
				}
				resultItem.put("concepts", concepts);
				resultItem.put("props", props);
				resultItem.put("methods", methods);
				resultItem.put("entitys", entitys);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultItem;
	}

	/**
	 * 获取某个领域指定节点拥有的上下级的节点数
	 *
	 * @param domain
	 * @param nodeid
	 * @return long 数值
	 */
	public long getRelationNodeCount(String domain, long nodeid) {
		long totalcount = 0;
		try {
			if (!StringUtils.isBlank(domain)) {
				String nodeSql = String.format("MATCH (n:`%s`) <-[r]->(m)  where id(n)=%s return count(m)", domain,
						nodeid);
				totalcount = neo4jUtil.getGraphValue(nodeSql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return totalcount;
	}

	/**
	 * 创建领域,默认创建一个新的节点,给节点附上默认属性
	 *
	 * @param domain
	 */
	public void createDomain(String domain) {
		try {
			String cypherSql = String.format(
					"create (n:`%s`{entitytype:0,name:''}) return id(n)", domain);
			neo4jUtil.excuteCypherSql(cypherSql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取/展开更多节点,找到和该节点有关系的节点
	 *
	 * @param domain
	 * @param nodeid
	 * @return
	 */
	public HashMap<String, Object> getMorerelationNode(String domain, String nodeid) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			String cypherSql = String.format("MATCH (n:`%s`) -[r]-(m) where id(n)=%s  return * limit 100", domain,
					nodeid);
			result = neo4jUtil.getGraphNodeAndShip(cypherSql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 更新节点名称
	 *
	 * @param domain
	 * @param nodeid
	 * @param nodename
	 * @return 修改后的节点
	 */
	public HashMap<String, Object> updateNodeName(String domain, String nodeid, String nodename) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		List<HashMap<String, Object>> graphNodeList = new ArrayList<HashMap<String, Object>>();
		try {
			String cypherSql = String.format("MATCH (n:`%s`) where id(n)=%s set n.name='%s' return n", domain, nodeid,
					nodename);
			graphNodeList = neo4jUtil.getGraphNode(cypherSql);
			if (graphNodeList.size() > 0) {
				return graphNodeList.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 创建单个节点
	 *
	 * @param domain
	 * @param entity
	 * @return
	 */
	public HashMap<String, Object> createNode(String domain, QAEntityItem entity) {
		HashMap<String, Object> rss = new HashMap<String, Object>();
		List<HashMap<String, Object>> graphNodeList = new ArrayList<HashMap<String, Object>>();
		try {
			if (entity.getUuid() != 0) {
				String sqlkeyval = neo4jUtil.getkeyvalCyphersql(entity);
				String cypherSql = String.format("match (n:`%s`) where id(n)=%s set %s return n", domain,
						entity.getUuid(), sqlkeyval);
				graphNodeList = neo4jUtil.getGraphNode(cypherSql);
			} else {
				entity.setColor("#ff4500");// 默认颜色
				entity.setR(30);// 默认半径
				String propertiesString = neo4jUtil.getFilterPropertiesJson(JSON.toJSONString(entity));
				String cypherSql = String.format("create (n:`%s` %s) return n", domain, propertiesString);
				graphNodeList = neo4jUtil.getGraphNode(cypherSql);
			}
			if (graphNodeList.size() > 0) {
				rss = graphNodeList.get(0);
				return rss;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return rss;
	}

	/**
	 * 批量创建节点和关系
	 *
	 * @param domain
	 *            领域
	 * @param sourcename
	 *            源节点
	 * @param relation
	 *            关系
	 * @param targetnames
	 *            目标节点数组
	 * @return
	 */
	public HashMap<String, Object> batchCreateNode(String domain, String sourcename, String relation,
			String[] targetnames) {
		HashMap<String, Object> rss = new HashMap<String, Object>();
		List<HashMap<String, Object>> nodes = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> ships = new ArrayList<HashMap<String, Object>>();
		try {
			String cypherSqlFmt = "create (n:`%s` {name:'%s',color:'#ff4500',r:30}) return n";
			String cypherSql = String.format(cypherSqlFmt, domain, sourcename);// 概念实体
			List<HashMap<String, Object>> graphNodeList = neo4jUtil.getGraphNode(cypherSql);
			if (graphNodeList.size() > 0) {
				HashMap<String, Object> sourceNode = graphNodeList.get(0);
				nodes.add(sourceNode);
				String sourceuuid = String.valueOf(sourceNode.get("uuid"));
				for (String tn : targetnames) {
					String targetnodeSql = String.format(cypherSqlFmt, domain, tn);
					List<HashMap<String, Object>> targetNodeList = neo4jUtil.getGraphNode(targetnodeSql);
					if (targetNodeList.size() > 0) {
						HashMap<String, Object> targetNode = targetNodeList.get(0);
						nodes.add(targetNode);
						String targetuuid = String.valueOf(targetNode.get("uuid"));
						String rSql = String.format(
								"match(n:`%s`),(m:`%s`) where id(n)=%s and id(m)=%s create (n)-[r:RE {name:'%s'}]->(m) return r",
								domain, domain, sourceuuid, targetuuid, relation);
						List<HashMap<String, Object>> rshipList = neo4jUtil.getGraphRelationShip(rSql);
						ships.addAll(rshipList);
					}

				}
			}
			rss.put("nodes", nodes);
			rss.put("ships", ships);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rss;
	}

	/**
	 * 批量创建下级节点
	 *
	 * @param domain
	 *            领域
	 * @param sourceid
	 *            源节点id
	 * @param entitytype
	 *            节点类型
	 * @param targetnames
	 *            目标节点名称数组
	 * @param relation
	 *            关系
	 * @return
	 */
	public HashMap<String, Object> batchCreateChildCode(String domain, String sourceid, Integer entitytype,
			String[] targetnames, String relation) {
		HashMap<String, Object> rss = new HashMap<String, Object>();
		List<HashMap<String, Object>> nodes = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> ships = new ArrayList<HashMap<String, Object>>();
		try {
			String cypherSqlFmt = "create (n:`%s`{name:'%s',color:'#ff4500',r:30}) return n";
			String cypherSql = String.format("match (n:`%s`) where id(n)=%s return n", domain, sourceid);
			List<HashMap<String, Object>> sourcenodeList = neo4jUtil.getGraphNode(cypherSql);
			if (sourcenodeList.size() > 0) {
				nodes.addAll(sourcenodeList);
				for (String tn : targetnames) {
					String targetnodeSql = String.format(cypherSqlFmt, domain, tn);
					List<HashMap<String, Object>> targetNodeList = neo4jUtil.getGraphNode(targetnodeSql);
					if (targetNodeList.size() > 0) {
						HashMap<String, Object> targetNode = targetNodeList.get(0);
						nodes.add(targetNode);
						String targetuuid = String.valueOf(targetNode.get("uuid"));
						// 创建关系
						String rSql = String.format(
								"match(n:`%s`),(m:`%s`) where id(n)=%s and id(m)=%s create (n)-[r:RE {name:'%s'}]->(m) return r",
								domain, domain, sourceid, targetuuid, relation);
						List<HashMap<String, Object>> shipList = neo4jUtil.getGraphRelationShip(rSql);
						ships.addAll(shipList);
					}
				}
			}
			rss.put("nodes", nodes);
			rss.put("ships", ships);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return rss;
	}

	/**
	 * 批量创建同级节点
	 *
	 * @param domain
	 *            领域
	 * @param entitytype
	 *            节点类型
	 * @param sourcenames
	 *            节点名称
	 * @return
	 */
	public List<HashMap<String, Object>> batchCreateSameCode(String domain, Integer entitytype, String[] sourcenames) {
		List<HashMap<String, Object>> rss = new ArrayList<HashMap<String, Object>>();
		try {
			String cypherSqlFmt = "create (n:`%s`{name:'%s',color:'#ff4500',r:30}) return n";
			for (String tn : sourcenames) {
				String sourcenodeSql = String.format(cypherSqlFmt, domain, tn, entitytype);
				List<HashMap<String, Object>> targetNodeList = neo4jUtil.getGraphNode(sourcenodeSql);
				rss.addAll(targetNodeList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rss;
	}

	/**
	 * 添加关系
	 *
	 * @param domain
	 *            领域
	 * @param sourceid
	 *            源节点id
	 * @param targetid
	 *            目标节点id
	 * @param ship
	 *            关系
	 * @return
	 */
	public HashMap<String, Object> createLink(String domain, long sourceid, long targetid, String ship) {
		HashMap<String, Object> rss = new HashMap<String, Object>();
		try {
			String cypherSql = String.format("MATCH (n:`%s`),(m:`%s`) WHERE id(n)=%s AND id(m) = %s "
					+ "CREATE (n)-[r:RE{name:'%s'}]->(m)" + "RETURN r", domain, domain, sourceid, targetid, ship);
			List<HashMap<String, Object>> cypherResult = neo4jUtil.getGraphRelationShip(cypherSql);
			if (cypherResult.size() > 0) {
				rss = cypherResult.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rss;
	}

	/**
	 * 更新关系
	 *
	 * @param domain
	 *            领域
	 * @param shipid
	 *            关系id
	 * @param shipname
	 *            关系名称
	 * @return
	 */
	public HashMap<String, Object> updateLink(String domain, long shipid, String shipname) {
		HashMap<String, Object> rss = new HashMap<String, Object>();
		try {
			String cypherSql = String.format("MATCH (n:`%s`) -[r]->(m) where id(r)=%s set r.name='%s' return r", domain,
					shipid, shipname);
			List<HashMap<String, Object>> cypherResult = neo4jUtil.getGraphRelationShip(cypherSql);
			if (cypherResult.size() > 0) {
				rss = cypherResult.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rss;
	}

	/**
	 * 删除节点(先删除关系再删除节点)
	 *
	 * @param domain
	 * @param nodeid
	 * @return
	 */
	public List<HashMap<String, Object>> deleteNode(String domain, long nodeid) {
		List<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			String nSql = String.format("MATCH (n:`%s`)  where id(n)=%s return n", domain, nodeid);
			result = neo4jUtil.getGraphNode(nSql);
			String rSql = String.format("MATCH (n:`%s`) <-[r]->(m) where id(n)=%s return r", domain, nodeid);
			neo4jUtil.getGraphRelationShip(rSql);
			String deleteRelationSql = String.format("MATCH (n:`%s`) <-[r]->(m) where id(n)=%s delete r", domain, nodeid);
			neo4jUtil.excuteCypherSql(deleteRelationSql);
			String deleteNodeSql = String.format("MATCH (n:`%s`) where id(n)=%s delete n", domain, nodeid);
			neo4jUtil.excuteCypherSql(deleteNodeSql);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 删除关系
	 *
	 * @param domain
	 * @param shipid
	 */
	public void deleteLink(String domain, long shipid) {
		try {
			String cypherSql = String.format("MATCH (n:`%s`) -[r]->(m) where id(r)=%s delete r", domain, shipid);
			neo4jUtil.excuteCypherSql(cypherSql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 段落识别出的三元组生成图谱
	 *
	 * @param domain
	 * @param entitytype
	 * @param operatetype
	 * @param sourceid
	 * @param rss
	 *            关系三元组
	 *            [[startname;ship;endname],[startname1;ship1;endname1],[startname2;ship2;endname2]]
	 * @return node relationship
	 */
	public HashMap<String, Object> createGraphByText(String domain, Integer entitytype, Integer operatetype,
			Integer sourceid, String[] rss) {
		HashMap<String, Object> rsList = new HashMap<String, Object>();
		try {
			List<Object> nodeIds = new ArrayList<Object>();
			List<HashMap<String, Object>> nodeList = new ArrayList<HashMap<String, Object>>();
			List<HashMap<String, Object>> shipList = new ArrayList<HashMap<String, Object>>();

			if (rss != null && rss.length > 0) {
				for (String item : rss) {
					String[] ns = item.split(";");
					String nodestart = ns[0];
					String ship = ns[1];
					String nodeend = ns[2];
					String nodestartSql = String.format("MERGE (n:`%s`{name:'%s',entitytype:'%s'})  return n", domain,
							nodestart, entitytype);
					String nodeendSql = String.format("MERGE (n:`%s`{name:'%s',entitytype:'%s'})  return n", domain,
							nodeend, entitytype);
					// 创建初始节点
					List<HashMap<String, Object>> startNode = neo4jUtil.getGraphNode(nodestartSql);
					// 创建结束节点
					List<HashMap<String, Object>> endNode = neo4jUtil.getGraphNode(nodeendSql);
					Object startId = startNode.get(0).get("uuid");
					if (!nodeIds.contains(startId)) {
						nodeIds.add(startId);
						nodeList.addAll(startNode);
					}
					Object endId = endNode.get(0).get("uuid");
					if (!nodeIds.contains(endId)) {
						nodeIds.add(endId);
						nodeList.addAll(endNode);
					}
					if (sourceid != null && sourceid > 0 && operatetype == 2) {// 添加下级
						String shipSql = String.format(
								"MATCH (n:`%s`),(m:`%s`) WHERE id(n)=%s AND id(m) = %s "
										+ "CREATE (n)-[r:RE{name:'%s'}]->(m)" + "RETURN r",
								domain, domain, sourceid, startId, "");
						List<HashMap<String, Object>> shipResult = neo4jUtil.getGraphRelationShip(shipSql);
						shipList.add(shipResult.get(0));
					}
					String shipSql = String.format("MATCH (n:`%s`),(m:`%s`) WHERE id(n)=%s AND id(m) = %s "
							+ "CREATE (n)-[r:RE{name:'%s'}]->(m)" + "RETURN r", domain, domain, startId, endId, ship);
					List<HashMap<String, Object>> shipResult = neo4jUtil.getGraphRelationShip(shipSql);
					shipList.addAll(shipResult);

				}
				rsList.put("node", nodeList);
				rsList.put("relationship", shipList);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return rsList;
	}

	public void batchCreateGraph(String domain, List<Map<String, Object>> params) {
		try {
			if (params != null && params.size() > 0) {
				String nodeStr = neo4jUtil.getFilterPropertiesJson(JSON.toJSONString(params));
				String nodeCypher = String
						.format("UNWIND %s as row " + " MERGE (n:`%s` {name:row.SourceNode,source:row.Source})"
								+ " MERGE (m:`%s` {name:row.TargetNode,source:row.Source})", nodeStr, domain, domain);
				neo4jUtil.excuteCypherSql(nodeCypher);
				String relationShipCypher = String.format("UNWIND %s as row " + " MATCH (n:`%s` {name:row.SourceNode})"
						+ " MATCH (m:`%s` {name:row.TargetNode})" + " MERGE (n)-[:RE{name:row.RelationShip}]->(m)",
						nodeStr, domain, domain);
				neo4jUtil.excuteCypherSql(relationShipCypher);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 批量导入csv
	 *
	 * @param domain
	 * @param csvUrl
	 * @param status
	 */
	public void batchInsertByCSV(String domain, String csvUrl, int status) {
		String loadNodeCypher1 = null;
		String loadNodeCypher2 = null;
		String addIndexCypher = null;
		addIndexCypher = " CREATE INDEX ON :" + domain + "(name);";
		loadNodeCypher1 = " USING PERIODIC COMMIT 500 LOAD CSV FROM '" + csvUrl + "' AS line " + " MERGE (:`" + domain
				+ "` {name:line[0]});";
		loadNodeCypher2 = " USING PERIODIC COMMIT 500 LOAD CSV FROM '" + csvUrl + "' AS line " + " MERGE (:`" + domain
				+ "` {name:line[1]});";
		// 拼接生产关系导入cypher
		String loadRelCypher = null;
		String type = "RE";
		loadRelCypher = " USING PERIODIC COMMIT 500 LOAD CSV FROM  '" + csvUrl + "' AS line " + " MATCH (m:`" + domain
				+ "`),(n:`" + domain + "`) WHERE m.name=line[0] AND n.name=line[1] " + " MERGE (m)-[r:" + type + "]->(n) "
				+ "	SET r.name=line[2];";
		neo4jUtil.excuteCypherSql(addIndexCypher);
		neo4jUtil.excuteCypherSql(loadNodeCypher1);
		neo4jUtil.excuteCypherSql(loadNodeCypher2);
		neo4jUtil.excuteCypherSql(loadRelCypher);
	}

	public void updateNodeFileStatus(String domain, long nodeId, int status) {
		try {
			String nodeCypher = String.format("match (n:`%s`) where id(n)=%s set n.hasfile=%s ", domain,nodeId, status);
			neo4jUtil.excuteCypherSql(nodeCypher);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void updateCorrdOfNode(String domain, String uuid, Double fx, Double fy) {
		String cypher = null;
		if (fx == null && fy==null) {
			cypher = " MATCH (n:" + domain +") where ID(n)=" + uuid
					+ " set n.fx=null, n.fy=null; ";
		} else {
			if ("0.0".equals(fx.toString()) && "0.0".equals(fy.toString())) {
				cypher = " MATCH (n:" + domain +") where ID(n)=" + uuid
						+ " set n.fx=null, n.fy=null; ";
			} else {
				cypher = " MATCH (n:" + domain +") where ID(n)=" + uuid
						+ " set n.fx=" + fx + ", n.fy=" + fy + ";";
			}
		}
		neo4jUtil.excuteCypherSql(cypher);
	}

	@Override
	public List<String> getNodesLabels() {
		String cypherSql = " CALL db.labels(); ";
		return neo4jUtil.getNodesLabelsEntityList(cypherSql);
	}

	@Override
	public List<String> getRelationshipType() {
		String cypherSql = " CALL db.relationshipTypes(); ";
		return neo4jUtil.getRelationshipTypeEntityList(cypherSql);
	}

	@Override
	public List<String> getNodesSchema() {
		String cypherSql = " CALL db.schema(); ";
		return neo4jUtil.getRelationshipTypeEntityList(cypherSql);
	}
}

你可能感兴趣的:(第三方服务,SQL,neo4j,开源,知识图谱)