Neo4j database operation performance optimization (Java)

When the sky is healthy, a gentleman strives to constantly strive for self-improvement; when the terrain is turbulent, a gentleman carries things with great virtue.

Everyone is lazy, but continuous learning is the foundation of a good life. Let’s encourage each other!

The articles are all for learning and organizing notes, mainly for sharing records. If there are any mistakes, please correct them and learn and progress together.

Neo4j database operation performance optimization

  • Preface
  • Implementation
    • 1. properties file
    • 2. Configuration class code
    • 3. Tool code
    • 4. Request control class

Foreword

Based on the previous article, Java implements operations on Neo4j database
Article link: https://blog.csdn.net/mo_sss/article/details/132082356

Based on the operation of neo4j database in the previous article, optimize the process of resource creation and closing and improve the efficiency of data processing.
The main part is to put resource creation in the configuration class without closing the resource, which will be much faster.

Detailed implementation

1. properties file

Neo4j database parameters read file neo4j.properties

neo4j.url=bolt://47.101.136.161:7687
neo4j.username=neo4j
neo4j.password=123456

Note: The database address and account password are all fake. Please configure them according to your own data

2. Configuration class code

Neo4jConfig.java

package com.data.config;


import lombok.Data;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Session;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


/**
* @ClassDescription: neo4j database parameter configuration class
* @Author: Li Bai
* @Date:2023/7/31 15:57
*/
@Data
@Component
//@PropertySource("neo4j.yml")
@PropertySource("neo4j.properties")
@ConfigurationProperties(prefix = "neo4j")
public class Neo4jConfig {<!-- -->
private String url;
   private String username;
   private String password;


@Bean
public Session neoSession() {<!-- -->

Driver driver = GraphDatabase.driver(url, AuthTokens.basic(username, password));
  Session session = driver.session();


       return session;
}

}

3. Tool code

Neo4jUtil.java

package com.data.utils.neo4j;


import com.alibaba.fastjson.JSONObject;
import com.data.config.Neo4jConfig;
import org.neo4j.driver.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


/**
* @ClassDescription: faster
* @Author: Li Bai
* @Date:2023/8/14 16:01
*/
@Component
public class Neo4jUtil {<!-- -->
@Autowired
Session session;
   private static Session neoSession;
@PostConstruct
public void s(){<!-- -->
neoSession = session;
}


/**
    * Add, delete and modify interface calls (create/delete/set)
  * @param cql
  */
public static void cds(String cql){<!-- -->
neoSession.run(cql);
}




/**
    * Query interface call (match)
    * @param cql
  * @return
  */
public static List m(String cql){<!-- -->



Result result = neoSession.run(cql);
// System.out.println("result: " + result);
  List list = new ArrayList();
  //Get each node
  while ( result.hasNext() )

{<!-- -->

Record record = result.next();
// System.out.println("record: " + record.get("n"));
// record.get("n");
  Map<String, Object> map = record.get("n").asMap();
  Set<Entry<String, Object>> set = map.entrySet();
  JSONObject nodeProperties = new JSONObject();
  //Traverse the information in each node, all in key-value form
  for(Map.Entry one : set){<!-- -->

nodeProperties.put(one.getKey().toString(),one.getValue());
  System.out.print(one.getKey() + "=" + one.getValue() + ";");
  }

System.out.println();
  list.add(nodeProperties);
// System.out.println("nodeProperties: " + nodeProperties);
  }

list.stream().sorted();
// System.out.println(list);
  return list;
}




/**
    * Check whether there is an interface call on the node
  * @param cql
  * @return
  */
public static Boolean checkNode(String cql){<!-- -->

Result result = neoSession.run(cql);


       return result.hasNext();
}
}

4. Request control class

To operate the database, just replace Neo4jUtils in the code in the previous article with Neo4jUtil.
Neo4jController.java

package com.data.neo4j;


import com.alibaba.fastjson.JSONObject;
import com.data.neo4j.entity.UserNode;
import com.data.utils.neo4j.Neo4jUtil;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
* @ClassDescription: Request to call-neo4j data operation
* @Author: Li Bai
* @Date:2023/7/31 8:27
*/
@RestController
@RequestMapping("/neo4j-part")
public class Neo4jController {<!-- -->


/**
    * New node-user----------------------Problem: strings need to be escaped with backslashes when used directly, and an error will be reported if they are filled in in the form of variables. .
  */
@PostMapping("/add")
public void add(/*@RequestParam("name")String name*/){<!-- -->

String name = "libai666";
  String cql = "create (u:User {name:"" + name + "", Group:"internal", email:"[email protected]"})";
  Neo4jUtil.cds(cql);
}


/**
    *------------------------------------------------ ---New node-------------------------------------------------- ----------
   */
  /**
    * New users
  */
@PostMapping("/addDevice")
public void addDevice(/*@RequestParam("deviceIdPre")String deviceIdPre*/){<!-- -->

String deviceGroup = "internal";
  //Create twenty devices
  for (int i = 1; i < 21; i + + ) {<!-- -->
if (i<10){<!-- -->

String deviceIdPre = "UA000";
  String cql = "create (d:Device {deviceId:" + """ + deviceIdPre + i + """ + ", deviceGroup:" + """ + deviceGroup + """ + "})" ;
  Neo4jUtil.cds(cql);
  }else {<!-- -->

String deviceIdPre = "UA00";
  String cql = "create (d:Device {deviceId:" + """ + deviceIdPre + i + """ + ", deviceGroup:" + """ + deviceGroup + """ + "})" ;
  Neo4jUtils.cds(cql);
  }

}

}


/**
    * Add new equipment
  */
@PostMapping("/addUser")
public void addUser(){<!-- -->
//User Info
  UserNode un1 = new UserNode("cx","internal","[email protected]");
  UserNode un2 = new UserNode("zzw","internal","[email protected]");
  UserNode un3 = new UserNode("cxl","internal","[email protected]");
  UserNode un4 = new UserNode("ljk","internal","[email protected]");
  UserNode un5 = new UserNode("bsj","internal","[email protected]");
  UserNode un6 = new UserNode("wzw","internal","[email protected]");
  UserNode un7 = new UserNode("wgx","internal","[email protected]");
  UserNode un8 = new UserNode("jxh","internal","[email protected]");
  UserNode un9 = new UserNode("wt","internal","[email protected]");
  List<UserNode> list = new ArrayList();
  list.add(un1);
  list.add(un2);
  list.add(un3);
  list.add(un4);
  list.add(un5);
  list.add(un6);
  list.add(un7);
  list.add(un8);
  list.add(un9);
  //Create 9 users
  for (int i = 0; i < list.size(); i + + ) {<!-- -->

UserNode u = list.get(i);
  String cql = "create (u:User {name:"" + u.getUserName() + "", userGroup:"" + u.getUserGroup() + "",email:"" + u. getEmail() + ""})";
  Neo4jUtil.cds(cql);
  }

}


/**
    *------------------------------------------------ ---Query node------------------------------------------------ ----------
   */


  /**
    * Query all node information
  * @return
  */
@GetMapping("/searchAll")
public JSONObject searchAll(){<!-- -->

String cql = "match (n) return n";
  List m = Neo4jUtil.m(cql);
  JSONObject listJson = new JSONObject();
  listJson.put("allNodes",m);
       return listJson;
}


/**
    * Query all node information of the specified label
  * @param label label
  * @return
  */
@GetMapping("/searchLabelNodes")
public JSONObject searchLabelNodes(@RequestParam("label")String label){<!-- -->

String cql = "match (n:" + label + ") return n";
  List m = Neo4jUtil.m(cql);
  JSONObject listJson = new JSONObject();
  listJson.put("labelNodes",m);
       return listJson;
}


/**
    * Query specific node information--Query the specific node of the device
  * @param deviceId device number
  * @return
  */
@GetMapping("/searchOneDevice")
public JSONObject searchOneDevice(@RequestParam("deviceId")String deviceId){<!-- -->

String cql = "match (n:Device{deviceId:"" + deviceId + ""}) return n";
  List m = Neo4jUtil.m(cql);
  JSONObject listJson = new JSONObject();
  listJson.put("device",m);
       return listJson;
}


/**
    * Query specific node information--Query the specific node of the device
  * @param name username
  * @return
  */
@GetMapping("/searchOneUser")
public JSONObject searchOneUser(@RequestParam("name")String name){<!-- -->

String cql = "match (n:User{name:"" + name + ""}) return n";
  List m = Neo4jUtil.m(cql);
  JSONObject listJson = new JSONObject();
  listJson.put("user",m);
       return listJson;
}


/**
    *------------------------------------------------ ---Delete node------------------------------------------------ ----------
   */
  /**
    * Delete all nodes
  */
@DeleteMapping("/deleteAllNodes")
public void deleteAllNodes(){<!-- -->

String cql = "match(n) delete n";
  Neo4jUtil.cds(cql);
}


/**
    * Delete all nodes with the same label
  * @param label label
  */
@DeleteMapping("/deleteLabelAllNodes")
public void deleteLabelAllNodes(@RequestParam("label")String label){<!-- -->

String cql = "match(n:" + label + ") delete n";
  Neo4jUtil.cds(cql);
}


/**
    * Delete the specified node
  * @param name username
  */
@DeleteMapping("/deleteOneUser")
public void deleteOneUser(@RequestParam("name")String name){<!-- -->

String cql = "match(n:User{name:"" + name + ""}) delete n";
  Neo4jUtil.cds(cql);
}


/**
    * Delete the specified node
  * @param deviceId device number
  */
@DeleteMapping("/deleteOneDevice")
public void deleteOneDevice(@RequestParam("deviceId")String deviceId){<!-- -->

String cql = "match(n:Device{deviceId:"" + deviceId + ""}) delete n";
  Neo4jUtil.cds(cql);
}


/**
    *------------------------------------------------ ---Modify node------------------------------------------------ ----------
   */
  /**
    * Modify user group and user mailbox based on user name
  * @param name username
  * @param userGroup user group
  * @param email User email
  */
@PutMapping("/updateUser")
public void updateUser(@RequestParam("name")String name,
  @RequestParam("userGroup")String userGroup,
  @RequestParam("email")String email){<!-- -->

String cql = "match(n:User{name:"" + name + ""}) set n.userGroup="" + userGroup + "",n.email="" + email + "\ "";
  Neo4jUtil.cds(cql);
}


/**
    * Modify the device group based on deviceId
  * @param deviceId device number
  * @param deviceGroup device group
  */
@PutMapping("/updateDevice")
public void updateDevice(@RequestParam("deviceId")String deviceId,
  @RequestParam("deviceGroup")String deviceGroup){<!-- -->

String cql = "match(n:Device{deviceId:"" + deviceId + ""}) set n.deviceGroup="" + deviceGroup + """;
  Neo4jUtil.cds(cql);
}




/**
    *------------------------------------------------ ---Create relationship------------------------------------------------ ----------
   */
  /**
    * Create a relationship between users and devices
  * @param name username
  * @param deviceId device number
  */
@PostMapping("/createR")
public void createR(@RequestParam("name")String name,
  @RequestParam("deviceId")String deviceId){<!-- -->

Date date = new Date();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd hhmmss");
  String dateStr = sdf.format(date);
  String cql1 = "match(u:User{name:"" + name + ""}),(d:Device{deviceId:"" + deviceId + ""})create (u)-[r: Borrow{date:"" + dateStr + ""}]->(d)";
  Neo4jUtil.cds(cql1);
  String cql2 = "match(u:User{name:"" + name + ""}),(d:Device{deviceId:"" + deviceId + ""})create (u)<-[r :Belong{date:"" + dateStr + ""}]-(d)";
  Neo4jUtil.cds(cql2);
}


/**
    *------------------------------------------------ ---Query relationship------------------------------------------------ ----------
   */
  /**
    * Query the borrowed equipment under the specified user name
  * @param name username
  * @return
  */
@GetMapping("/searchU2D")
public JSONObject searchU2D(@RequestParam("name")String name){<!-- -->

JSONObject u2dJson = new JSONObject();
  String cql = "match(u:User{name:"" + name + ""})-[r:Borrow]->(n) return n";
  List m = Neo4jUtil.m(cql);
  u2dJson.put("u2dList",m);
       return u2dJson;
}


/**
    * Query the user list of the specified device
  * @param deviceId device number
  * @return
  */
@GetMapping("/searchD2U")
public JSONObject searchD2U(@RequestParam("deviceId")String deviceId){<!-- -->

JSONObject d2uJson = new JSONObject();
  String cql = "match(d:Device{deviceId:"" + deviceId + ""})-[r:Belong]->(n) return n";
  List m = Neo4jUtil.m(cql);
  d2uJson.put("d2uList",m);
       return d2uJson;
}


/**
    *------------------------------------------------ ---Delete relationship------------------------------------------------ ----------
   */
  /**
    * Delete the relationship between the specified user and the specified device
  * @param name username
  * @param deviceId device number
  */
@DeleteMapping("/deleteU2DR")
public void deleteU2DR(@RequestParam("name")String name,
  @RequestParam("deviceId")String deviceId){<!-- -->

String cql1 = "match(u:User{name:"" + name + ""})-[r:Borrow]->(d:Device{deviceId:"" + deviceId + ""}) delete r";
  String cql2 = "match(u:User{name:"" + name + ""})<-[r:Belong]-(d:Device{deviceId:"" + deviceId + ""}) delete r";
  Neo4jUtil.cds(cql1);
  Neo4jUtil.cds(cql2);
}


/**
    * Delete the relationship between the specified user and all devices
  * @param name username
  */
@DeleteMapping("/deleteU2AllDR")
public void deleteU2AllDR(@RequestParam("name")String name){<!-- -->

String cql1 = "match(u:User{name:"" + name + ""})-[r:Borrow]->(d:Device) delete r";
  String cql2 = "match(u:User{name:"" + name + ""})<-[r:Belong]-(d:Device) delete r";
  Neo4jUtil.cds(cql1);
  Neo4jUtil.cds(cql2);
}


/**
    * Delete the relationship between the specified device and all users
  * @param deviceId device number
  */
@DeleteMapping("/deleteD2AllUR")
public void deleteD2AllUR(@RequestParam("deviceId")String deviceId){<!-- -->

String cql1 = "match(u:User)-[r:Borrow]->(d:Device{deviceId:"" + deviceId + ""}) delete r";
  String cql2 = "match(u:User)<-[r:Belong]-(d:Device{deviceId:"" + deviceId + ""}) delete r";
  Neo4jUtil.cds(cql1);
  Neo4jUtil.cds(cql2);
}




/**
    *------------------------------------------------ ---Modify relationship------------------------------------------------ ----------
   */
  /**
    * Modify the relationship between the specified user and the specified device
  * @param name username
  * @param deviceId device number
  * @param expire device borrowing time
  */
@PutMapping("/updateU2DR")
public void updateU2DR(@RequestParam("name")String name,
  @RequestParam("deviceId")String deviceId,
  @RequestParam("expire")String expire){<!-- -->

String cql1 = "match(u:User{name:"" + name + ""})-[r:Borrow]->(d:Device{deviceId:"" + deviceId + ""}) set r.date="" + expire + """;
  String cql2 = "match(u:User{name:"" + name + ""})<-[r:Belong]-(d:Device{deviceId:"" + deviceId + ""}) set r.date="" + expire + """;
  Neo4jUtil.cds(cql1);
  Neo4jUtil.cds(cql2);
}


/**
    * Modify the relationship between the specified user and all devices
  * @param name username
  * @param expire device borrowing time
  */
@PutMapping("/updateU2AllDR")
public void updateU2AllDR(@RequestParam("name")String name,
  @RequestParam("expire")String expire){<!-- -->

String cql1 = "match(u:User{name:"" + name + ""})-[r:Borrow]->(d) set r.date="" + expire + """;
  String cql2 = "match(u:User{name:"" + name + ""})<-[r:Belong]-(d) set r.date="" + expire + """;
  Neo4jUtil.cds(cql1);
  Neo4jUtil.cds(cql2);
}


/**
    * Modify the relationship between the specified device and all users
  * @param deviceId device number
  * @param expire device borrowing time
  */
@PutMapping("/updateD2AllUR")
public void updateD2AllUR(@RequestParam("deviceId")String deviceId,
  @RequestParam("expire")String expire){<!-- -->

String cql1 = "match(u)-[r:Borrow]->(d:Device{deviceId:"" + deviceId + ""}) set r.date="" + expire + """;
  String cql2 = "match(u)<-[r:Belong]-(d:Device{deviceId:"" + deviceId + ""}) set r.date="" + expire + """;
  Neo4jUtil.cds(cql1);
  Neo4jUtil.cds(cql2);
}



}