Java连接Neo4j,Neo4j查询实体与关系,Neo4j增加关系,Neo4j增加实体,Neo4j修改实体

Java连接Neo4j,Neo4j查询实体与关系,Neo4j增加关系,Neo4j增加实体

  1. 第一步 添加依赖

        
            org.neo4j.driver
            neo4j-java-driver
            4.2.0
        
  1. 第二步 ,建议连接{注意连接地址ip端口为Neo4j服务暴露端口7687,非可视化页面7474端口}
private static Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "neo4j"));
  1. 第三部,查询
import org.neo4j.driver.*;
import org.neo4j.driver.internal.InternalNode;
import org.neo4j.driver.internal.InternalPath;
import org.neo4j.driver.internal.InternalResult;
import org.neo4j.driver.types.Node;
import org.neo4j.driver.types.Relationship;
// 非下列依赖jar
//import org.neo4j.ogm.model.Property;
//import org.neo4j.ogm.model.Result;
//import org.neo4j.ogm.response.model.NodeModel;
//import org.neo4j.ogm.session.Session;

Session session = driver.session();
Result result = null;
String neo4jCql = "match p=(a:label1:label2{propertyDemo:'propertyValue'})-[*..1]->(b:label1:label2)-[*..1]-(c:label1:label2:`label3`) return p"
String neo4jCql = "match p=(a:label1:label2{propertyDemo:'propertyValue'})<-[:`关系label`]->(b:label1:label2) return p"
// 原CQL  String neo4jCql = "match p=(a:label1:label2{propertyDemo:'propertyValue',propertyDemo2:'propertyValue2'})-[*..20]->(b:label1:label2:label3{propertyDemo:'propertyValue'}) return p limit 200";
        String neo4jCql = "";
        if (!ObjectUtils.isEmpty(nameFrom页面传值)){
            esopCql = "match p=(a:`"+页面传值label1+"`:`"+页面传值label2+"`{propertyDemo:%s"+"})-[r]->(b:`"+页面传值label1+"`:`"+页面传值label2+"`:`页面传值label3`{propertyDemo:%s"+"}) return p";
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("\"");
            stringBuilder.append(nameFrom页面传值);
            stringBuilder.append("\"");
            esopCql = String.format(neo4jCql,stringBuilder.toString(),stringBuilder.toString());
        }else {
           
        }


result = session.run( neo4jCql);

Map returnMapForD3 = new HashMap();
Map selfPointNodesMap = new HashMap();
HashSet> nodedatas = new HashSet>();// 存放所有的节点数据
HashSet> allRelationShips = new HashSet>();// 存放所有的关系节点数据
while (result.hasNext()){
    Record record = result.next();
    Map date = record.asMap();
    for (String key : date.keySet()) {
        Object object = date.get(key);
        InternalPath data = (InternalPath) object;// 强制转换
        Iterable allnodes = data.nodes();

        for (Node node : allnodes) {
            long nodeid = node.id();
            String colorValue = "#466630";
            Map nodedatamap = new HashMap();
            Map data1 = node.asMap();
            // 赋予根节点
            String valueFromKey = data1.get("实体属性key")+"";
            if ( "特定值".equals(valueFromKey )){
                rootId = nodeid+"";
            }
            String name = data1.get("Name")+"";
            if (name.equals(nameFrom页面传值)){
                rootId = nodeid+"";
            }

            Iterable labels = node.labels();
            List  labelsList = new ArrayList();
            if (null != labels){
                for (String label : labels) {
                    labelsList.add(label);
                    if (uniqueLabelsMap.containsKey(label+"")){
                        colorValue = uniqueLabelsMap.get(label+"");
                    }
                }
            }
            nodedatamap.put("color", colorValue);
            // 为了新增实体,规范概念
            nodedatamap.put("labels", labelsList);


            // 组装节点的属性
            for (String key1 : data1.keySet()) {
                nodedatamap.put(key1, data1.get(key1)+"");
                // 前端组件需要这个 name 字段
                nodedatamap.put("name", data1.get("Name")+"");

            }
            nodedatamap.put("id", nodeid+"");
            Map childMap = new HashMap<>();
            for (String key6 : nodedatamap.keySet()) {
                childMap.put(key6,nodedatamap.get(key6)+"");
                // 前端组件需要这个 name 字段
                childMap.put("name", nodedatamap.get("Name")+"");
            }
            childMap.put("labels", labelsList);
            nodedatamap.put("data",childMap);

            selfPointNodesMap.put(nodeid+"",nodedatamap);
            nodedatas.add(nodedatamap);
        }

        Iterable relationships = data.relationships();


        for (Relationship relationship : relationships) {
            Map shipdata = new HashMap();
            // 关系属性暂时没有
            /*Map data1 = relationship.asMap();// 添加关系的属性
            for (String key1 : data1.keySet()) {
                shipdata.put(key1, data1.get(key1));
            }*/
            long linkId = relationship.id();
            long source = relationship.startNodeId();// 起始节点id
            String type = relationship.type();
            long target = relationship.endNodeId();// 结束节点Id
            shipdata.put("linkId", linkId+"");// 添加关系id
            shipdata.put("from", source+"");// 添加起始节点id
            shipdata.put("text", type);     // 添加关系type
            shipdata.put("to", target+"");  // 添加目标节点id

            Map childMap = new HashMap<>();
            for (String key6 : shipdata.keySet()) {
                childMap.put(key6,shipdata.get(key6)+"");
            }
            shipdata.put("data", childMap);
            allRelationShips.add(shipdata);
        }


    }
}

session.close();


// 自指向问题
int selfPointNum = 0;
if (!CollectionUtils.isEmpty(allRelationShips)){
    for (Map relationShip : allRelationShips) {
        String linkId = relationShip.get("linkId") + "";
        String from = relationShip.get("from") + "";
        String text = relationShip.get("text") + "";
        String to = relationShip.get("to") + "";
        if (from.equals(to)){
            selfPointNum+=1;
            Map dataMap = selfPointNodesMap.get(from);
            dataMap.remove("data");
            dataMap.put("id","selfPoint"+selfPointNum);
            dataMap.put("selfPoint","true");
            String oldLabels = dataMap.get("labels") + "";
            String replace = oldLabels.replace("[", "");
            String replace2 = oldLabels.replace("]", "");
            String[] strings = replace2.split(",");
            List labelsList = new ArrayList<>();
            for (int i = 0; i < strings.length; i++) {
                String string = strings[i];
                labelsList.add(string);
            }
            Map childMap = new HashMap<>();
            for (Object key6 : dataMap.keySet()) {
                childMap.put(key6,dataMap.get(key6+"")+"");
                // 前端组件需要这个 name 字段
                childMap.put("name", dataMap.get("Name")+"");
            }
            childMap.put("labels",labelsList);
            dataMap.put("data",childMap);
            nodedatas.add(dataMap);
            // 组装新关系
            relationShip.put("to","selfPoint"+selfPointNum);

        }

    }
}


returnMapForD3.put("rootId", rootId);
returnMapForD3.put("nodes", nodedatas);
logger.info("(nodedatas.size());=====>"+nodedatas.size()+"");
returnMapForD3.put("links", allRelationShips);
logger.info("(allRelationShips.size());=====>"+allRelationShips.size()+"");




/*logger.info("nodedatas.toString()");
System.out.println(nodedatas.toString());
logger.info("allRelationShips.toString()");
System.out.println(allRelationShips.toString());

logger.info("returnMapForD3.toString()");
System.out.println(returnMapForD3.toString());*/
logger.info("结束时间======》"+new Date().getTime());
long time2 = new Date().getTime();
String lllll = (time2 - time1)+"";
long lll = time2 - time1;
logger.info("时间差===CQL查询执行时间===》"+lllll);
logger.info("时间差===CQL查询执行时间===》"+lll);
logger.info("rootId======》"+rootId+"");
return returnMapForD3;


session.close();


  1. 插入关系 demo
String addRelationCypherSql = "match (startNode:`"+label1+"`:`"+label2+"`{propertyKey:%s"+"}),(endNode:`"+label1+"`:`"+label2+"`{propertyKey:%s"+"}) create (startNode)-[r:`"+关系type值+"`]->(endNode) return r ";

StringBuilder stringBuilderFrom = new StringBuilder();
stringBuilderFrom.append("\"");
stringBuilderFrom.append(from);
stringBuilderFrom.append("\"");
StringBuilder stringBuilderTo = new StringBuilder();
stringBuilderTo.append("\"");
stringBuilderTo.append(to);
stringBuilderTo.append("\"");
addRelationCypherSql = String.format(addRelationCypherSql,stringBuilderFrom.toString(),stringBuilderTo);

Result result = session.run(addRelationCypherSql);
  1. 增加实体 demo
// 建立实体对象类
//节点实体类
public class Neo4jBasicNode implements Serializable {
  private static final long serialVersionUID = 1L;
  /**
   * id
   */
  private Long id;

  /**
   * 标签
   */
  private List labels;

  /**
   * 标签属性
   */
  private Map property;

  public Long getId() {
      return id;
  }

  public void setId(Long id) {
      this.id = id;
  }

  public List getLabels() {
      return labels;
  }

  public void setLabels(List labels) {
      this.labels = labels;
  }

  public Map getProperty() {
      return property;
  }

  public void setProperty(Map property) {
      this.property = property;
  }
}





/**
* init map序列号
*/
private static final ObjectMapper mapper = new ObjectMapper();

static {
   mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
}

public static String propertiesMapToPropertiesStr(Map map) {
   map.entrySet().removeIf(entry -> org.springframework.util.ObjectUtils.isEmpty(entry.getValue()));

   String s = null;
   try {
       s = mapper.writeValueAsString(map);
   } catch (JsonProcessingException e) {
       e.printStackTrace();
   }
   return s;
}

/**
 * 新增实体 拼接动态 Cql
 */
  @PostMapping("/edit/add")
  public AjaxResult add(@RequestBody Neo4jBasicNode neo4jBasicNode)
  {


      Session session = null;
      int num = 0;
      try {
          session = driver.session();
          String labels = "";
          if (!ObjectUtils.isEmpty(neo4jBasicNode.getLabels())) {
              labels = ":`" + String.join("`:`", neo4jBasicNode.getLabels()) + "`";
          }


          String property = "";
          if (!ObjectUtils.isEmpty(neo4jBasicNode.getProperty())) {
              property = propertiesMapToPropertiesStr(neo4jBasicNode.getProperty());
          }
  

          String cypherSql = String.format("%s(%s%s)","create", labels, property);
          
          Result result = session.run(cypherSql);
          num = 1;

      } catch (Exception e) {
          num = 0;
          e.printStackTrace();
          logger.error(e.getMessage());
      } finally {
          session.close();
      }
      return toAjax(num);



  }
  1. 更新实体 demo
/**
     * 修改实体节点
     */
    @PutMapping("/edit/edit")
    public AjaxResult edit(@Validated @RequestBody Neo4jBasicNode neo4jBasicNode)
    {
        Session session = null;
        Result result = null;
        int num = 0;
        try {
            session = driver.session();
            Map propertyMap = neo4jBasicNode.getProperty();
            String ID = propertyMap.get("ID")+"";

            String labels = "";
            if (!ObjectUtils.isEmpty(neo4jBasicNode.getLabels())) {
                labels = ":`" + String.join("`:`", neo4jBasicNode.getLabels()) + "`";
            }
            Map noMap = new HashMap<>();
            noMap.put("ID","id");
            noMap.put("id","id");
            noMap.put("labels","id");
            String propertyStr = "SET ";
            for (String key : propertyMap.keySet()) {

                if (!noMap.containsKey(key+"")){
                    String setStr = "node."+key+"= '"+(propertyMap.get(key)+""+"',");
                    propertyStr+=setStr;
                }

            }
            String propertyStrSubstring = propertyStr.substring(0, propertyStr.length() - 1);
            /*if (!ObjectUtils.isEmpty(neo4jBasicNode.getProperty())) {
                propertyStr = propertiesMapToPropertiesStr(neo4jBasicNode.getProperty());
            }*/


            String format = String.format("MATCH(%s%s)", labels, propertyStr);

            String updateByParam =  "MATCH (node"+labels+"{ID:'"+ID+"'}) "+propertyStrSubstring+" RETURN node";
            logger.info("修改实体nodeId:====>"+(ID+"")+"{CQL}==>{"+updateByParam+"}");
            result = session.run(updateByParam);

            num = 1;

            logger.info("修改实体nodeId:====>"+(ID+"")+"成功");
        } catch (NumberFormatException e) {
            num = 0;
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            session.close();
        }

        /*MATCH (node:`label1`:`label2`:`label3`{唯一属性名Key:'唯一属性名Key对应值'})
        SET 
        node.key1= 'value1"',
        node.key2= 'value2',
        node.key2= 'value3'
        RETURN node*/

        return toAjax(num);


    }

你可能感兴趣的:(java,Neo4j图数据库,java,neo4j,知识图谱)