您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码:  验证码,看不清楚?请点击刷新验证码 必填



  求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Model Center   模型库  
会员   
   
基于 UML 和EA进行分析设计
6月23-24日 北京+线上
人工智能、机器学习 TensorFlow
6月30日-7月1日 直播
图数据库与知识图谱
8月21日-22日 北京+线上
     
   
 
 订阅
Neo4j的使用与Java调用实例
 
作者:Royi666
  68  次浏览      4 次
2025-6-19
 
编辑推荐:
本文主要介绍了Neo4j的使用与Java调用实例相关内容。希望对你的学习有帮助。
本文来自于微信公众号CSDN,由火龙果软件Linda编辑、推荐。

一. Neo4j简介:

Neo4j是一个高性能的,NoSQL图形数据库,它将结构化数据存储在网络上而不是表中。它是一个嵌入式的、基于磁盘的、具备完全的事务特性的Java持久化引擎,但是它将结构化数据存储在网络(从数学角度叫做图)上而不是表中。Neo4j也可以被看作是一个高性能的图引擎,该引擎具有成熟数据库的所有特性。程序员工作在一个面向对象的、灵活的网络结构下而不是严格、静态的表中——但是他们可以享受到具备完全的事务特性、企业级的数据库的所有好处。

在一个图中包含两种基本的数据类型:Nodes(节点) 和 Relationships(关系)。Nodes 和 Relationships 包含key/value形式的属性。Nodes通过Relationships所定义的关系相连起来,形成关系型网络结构。

相比其他NoSQL数据库,Neo4j的特点在于可以建立关系,达到数据关联的目的。从某些方面来说,我觉得它甚至可以取代关系型数据库,而且不需要事先定义表结构,字段扩展非常方便。

它使用的查询语言是Cypher。

二. Neo4j的核心概念:

1. Nodes(节点)

节点包含多个标签和属性,就像是一个地铁站。

一个节点就是一条数据。

2. Relations(关系)

关系是用来连接两个节点的,也可以包含多个标签和属性,就像是地铁站之间的线路。

一个关系也是一条数据。

关系包括进和出两种方向。

3. Properties(属性)

类似于关系型数据库里面的字段,不用事先定义,可以动态添加。

4. Labels(标签)

表示节点或者关系的类型,可以有多个,使查询更加方便和高效。

三. Neo4j的配置和使用:

下载最新的Neo4j:http://neo4j.com/download/

解压后移动到Neo4j下的bin目录,启动命令:neo4j.bat console

默认端口:7474

可在conf/neo4j.conf里面修改配置

在浏览器输入localhost:7474,登录Neo4j进行操作,默认用户名/密码:neo4j/neo4j,登陆后需要立刻修改密码。

①:Cypher查询语句

②:各种Labels及其数量

③:节点和关系的图形界面

④:某节点包含的属性

四. Cypher的基本语法:

1. 创建节点:

CREATE (n:Label {name:"L1", type:"T1"})

可以理解成:INSERT INTO Label(name, type) VALUES("L1", "T1")

n是变量名,可以任意。Label是标签,可以有多个。{}里面是属性,可以有多个。

这个创建节点的例子中,包含了2个标签:

CREATE (n:Label:Test {name:"L1", type:"T1"})

2. 查找节点:

MATCH(a:Test) WHERE a.name="L1" RETURN a;

3. 创建多个节点和关系:

CREATE (节点1),(节点2),(节点3),(节点1)-[关系1]->(节点2),(节点2)-[关系2]->(节点3)

例:CREATE (a:Node), (b:Node), (a)-[:Relate]->(b)

如果已有Node,只想添加关联,可用下面这种方法:

MATCH(a:Node),(b:Node) WHERE ID(a)=230 AND ID(b)=231 CREATE (b)-[:R]->(a)

4. 模式匹配:

根据关联进行数据查询。

MATCH (a)-[:Have]-(b)-[:Have]-(c)-[:Have]-(d) WHERE a.name="G1" RETURN a,b,c,d

5. 更新节点:

MATCH(n:Label) WHERE n.name="N2" SET n.update = "2018-06-26"

6. 删除节点:

MATCH(n) WHERE ID(n)=100 DELETE n

7. 查看语句分析:

在查询语句前加上

EXPLAIN

PROFILE

 

五. Java实现的接口和实例:

我用的是SpringBoot的项目,可以直接启动ConsumerClientApplication,不用放到Tomcat下。

1. pom.xml中引入neo4j的jar包:

  1. <dependency>
  2. <!-- 服务器开发需要的jar包 -->
  3. <groupId>org.neo4j.driver</groupId>
  4. <artifactId>neo4j-java-driver</artifactId>
  5. <version>1.5.0</version>
  6. </dependency>
  7. <dependency>
  8. <!-- 嵌入式开发需要的jar包 -->
  9. <groupId>org.neo4j</groupId>
  10. <artifactId>neo4j</artifactId>
  11. <version>3.3.4</version>
  12. </dependency>

 

2. 创建Code对象,用来传递参数:

  1. package com.inesa.neo4j.entity;
  2. public class Code {
  3. private String id;
  4. private String node;
  5. private String relation;
  6. private String property;
  7. private String label;
  8. private String nodeFromId;
  9. private String nodeFromLabel;
  10. private String nodeToId;
  11. private String nodeToLabel;
  12. private String where;
  13. private String update;
  14. private String result;
  15. public String getNode() {
  16. return node;
  17. }
  18. public void setNode(String node) {
  19. this.node = node;
  20. }
  21. public String getRelation() {
  22. return relation;
  23. }
  24. public void setRelation(String relation) {
  25. this.relation = relation;
  26. }
  27. public String getProperty() {
  28. return property;
  29. }
  30. public void setProperty(String property) {
  31. this.property = property;
  32. }
  33. public String getLabel() {
  34. return label;
  35. }
  36. public void setLabel(String label) {
  37. this.label = label;
  38. }
  39. public String getNodeFromId() {
  40. return nodeFromId;
  41. }
  42. public void setNodeFromId(String nodeFromId) {
  43. this.nodeFromId = nodeFromId;
  44. }
  45. public String getNodeToId() {
  46. return nodeToId;
  47. }
  48. public void setNodeToId(String nodeToId) {
  49. this.nodeToId = nodeToId;
  50. }
  51. public String getId() {
  52. return id;
  53. }
  54. public void setId(String id) {
  55. this.id = id;
  56. }
  57. public String getNodeFromLabel() {
  58. return nodeFromLabel;
  59. }
  60. public void setNodeFromLabel(String nodeFromLabel) {
  61. this.nodeFromLabel = nodeFromLabel;
  62. }
  63. public String getNodeToLabel() {
  64. return nodeToLabel;
  65. }
  66. public void setNodeToLabel(String nodeToLabel) {
  67. this.nodeToLabel = nodeToLabel;
  68. }
  69. public String getWhere() {
  70. return where;
  71. }
  72. public void setWhere(String where) {
  73. this.where = where;
  74. }
  75. public String getUpdate() {
  76. return update;
  77. }
  78. public void setUpdate(String update) {
  79. this.update = update;
  80. }
  81. public String getResult() {
  82. return result;
  83. }
  84. public void setResult(String result) {
  85. this.result = result;
  86. }
  87. }

 

3. 创建Controller,添加接口:

  1. package com.inesa.neo4j.controller;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import org.neo4j.driver.v1.AuthTokens;
  7. import org.neo4j.driver.v1.Driver;
  8. import org.neo4j.driver.v1.GraphDatabase;
  9. import org.neo4j.driver.v1.Record;
  10. import org.neo4j.driver.v1.Session;
  11. import org.neo4j.driver.v1.StatementResult;
  12. import static org.neo4j.driver.v1.Values.parameters;
  13. import org.springframework.web.bind.annotation.RequestBody;
  14. import org.springframework.web.bind.annotation.RequestMapping;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import com.inesa.common.entity.RestfulResult;
  17. import com.inesa.common.utils.CommUtils;
  18. import com.inesa.common.utils.Constants;
  19. import com.inesa.neo4j.entity.Code;
  20. /**
  21. * Controller
  22. *
  23. * @author sun
  24. * @version 2018-06-01
  25. */
  26. @RestController
  27. @RequestMapping(value = "neo4j")
  28. public class CodeController {
  29. private Driver createDrive(){
  30. return GraphDatabase.driver
    ( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "admin" ) );
  31. }
  32. @RequestMapping(value = "test")
  33. public void test(HttpServletRequest request,
    HttpServletResponse response) {
  34. RestfulResult restfulResult = new RestfulResult();
  35. try{
  36. Driver driver = createDrive();
  37. Session session = driver.session();
  38. session.run( "CREATE (a:Person {name: {name}, title: {title}})",
  39. parameters( "name", "Arthur001", "title", "King001" ) );
  40. StatementResult result = session.run
    ( "MATCH (a:Person) WHERE a.name = {name} " +

  41. "RETURN a.name AS name, a.title AS title",
  42. parameters( "name", "Arthur001" ) );
  43. while ( result.hasNext() )
  44. {
  45. Record record = result.next();
  46. System.out.println( record.get( "title" ).asString() + "
    " + record.get( "name" ).asString() + " " + record.get( "id" ).asString() );
  47. }
  48. session.close();
  49. driver.close();
  50. }catch(Exception e){
  51. restfulResult.setResult(Constants.RESULT_STATE_ERROR);
  52. restfulResult.setMessage(e.getMessage());
  53. }
  54. CommUtils.printDataJason(response, restfulResult);
  55. }
  56. @RequestMapping(value = "save")
  57. public void save(HttpServletRequest
    request, HttpServletResponse response,
  58. @RequestBody Code code) {
  59. RestfulResult restfulResult = new RestfulResult();
  60. try{
  61. Driver driver = createDrive();
  62. Session session = driver.session();
  63. StatementResult result = session.ru(an
    ( "CREATE :" + code.getLabel() + "
    {" + code.getProperty() + "}) return a");
  64. while (result.hasNext())
  65. {
  66. Record record = result.next();
  67. restfulResult.setData(record.fields().get
    (0).value().toString().replace("node<", "").replace(">", ""));
  68. }
  69. session.close();
  70. driver.close();
  71. }catch(Exception e){
  72. restfulResult.setResult(Constants.RESULT_STATE_ERROR);
  73. restfulResult.setMessage(e.getMessage());
  74. }
  75. CommUtils.printDataJason(response, restfulResult);
  76. }
  77. @RequestMapping(value = "update")
  78. public void update(HttpServletRequest
    request, HttpServletResponse response,
  79. @RequestBody Code code) {
  80. RestfulResult restfulResult = new RestfulResult();
  81. try{
  82. Driver driver = createDrive();
  83. Session session = driver.session();
  84. StatementResult result = session.run("MATCH
    (a:" + code.getLabel() + ") WHERE a." +
    code.getWhere() + " SET a." + code.getUpdate() + " return COUNT(a)");
  85. while (result.hasNext())
  86. {
  87. Record record = result.next();
  88. restfulResult.setData
    (record.fields().get(0).value().toString());
  89. }
  90. session.close();
  91. driver.close();
  92. }catch(Exception e){
  93. restfulResult.setResult(Constants.RESULT_STATE_ERROR);
  94. restfulResult.setMessage(e.getMessage());
  95. }
  96. CommUtils.printDataJason(response, restfulResult);
  97. }
  98. @RequestMapping(value = "delete")
  99. public void delete(HttpServletRequest
    request, HttpServletResponse response,
  100. @RequestBody Code code) {
  101. RestfulResult restfulResult = new RestfulResult();
  102. try{
  103. Driver driver = createDrive();
  104. Session session = driver.session();
  105. session.run( "match (n)
    where ID(n) = " + code.getId() +" detach delete n");
  106. session.close();
  107. driver.close();
  108. }catch(Exception e){
  109. restfulResult.setResult(Constants.RESULT_STATE_ERROR);
  110. restfulResult.setMessage(e.getMessage());
  111. }
  112. CommUtils.printDataJason(response, restfulResult);
  113. }
  114. @RequestMapping(value = "search")
  115. public void search(HttpServletRequest
    request, HttpServletResponse response,
  116. @RequestBody Code code) {
  117. RestfulResult restfulResult = new RestfulResult();
  118. try{
  119. Driver driver = createDrive();
  120. Session session = driver.session();
  121. StatementResult result = session
    .run("MATCH " + code.getProperty() +
  122. " MATCH " + code.getRelation() +
  123. " WHERE " + code.getWhere() +
  124. " RETURN " + code.getResult());
  125. List<String> resultList = new ArrayList<String>();
  126. while ( result.hasNext() )
  127. {
  128. Record record = result.next();
  129. resultList.add(record.get("id").toString()
    + " " + record.get("name").toString());
  130. }
  131. session.close();
  132. driver.close();
  133. restfulResult.setData(resultList);
  134. }catch(Exception e){
  135. restfulResult.setResult(Constants.RESULT_STATE_ERROR);
  136. restfulResult.setMessage(e.getMessage());
  137. }
  138. CommUtils.printDataJason(response, restfulResult);
  139. }
  140. @RequestMapping(value = "relate")
  141. public void relate(HttpServletRequest
    request, HttpServletResponse response,
  142. @RequestBody Code code) {
  143. RestfulResult restfulResult = new RestfulResult();
  144. try{
  145. Driver driver = createDrive();
  146. Session session = driver.session();
  147. session.run("MATCH
    (a:" + code.getNodeFromLabel() + "),
    (b:" + code.getNodeToLabel() + ") " +
  148. "WHERE ID(a) = " +
    code.getNodeFromId() + " AND ID(b) = " + code.getNodeToId()
  149. + " CREATE (a)-[:" + code.getRelation() + "]->(b)");
  150. session.close();
  151. driver.close();
  152. }catch(Exception e){
  153. restfulResult.setResult(Constants.RESULT_STATE_ERROR);
  154. restfulResult.setMessage(e.getMessage());
  155. }
  156. CommUtils.printDataJason(response, restfulResult);
  157. }
  158. //private static final String
    DB_PATH = "D:/neo4j/data/databases/graph.db";
  159. //GraphDatabaseService graphDb;
  160. /*@RequestMapping(value = "save")
  161. public void save(HttpServletRequest
    request, HttpServletResponse response,
  162. @RequestBody Code code) {
  163. RestfulResult restfulResult = new RestfulResult();
  164. try{
  165. if (graphDb == null)
  166. this.graphDb = new
    GraphDatabaseFactory().newEmbeddedDatabase(new File(DB_PATH));
  167. registerShutdownHook(graphDb);
  168. Transaction tx = graphDb.beginTx();
  169. Node node = this.graphDb.createNode();
  170. Label label = DynamicLabel.label(code.getLabel());
  171. node.addLabel(label);
  172. node.setProperty("Name", code.getProperty());
  173. tx.success();
  174. restfulResult.setData(node.getId());
  175. }catch(Exception e){
  176. restfulResult.setResult(Constants.RESULT_STATE_ERROR);
  177. restfulResult.setMessage(e.getMessage());
  178. }
  179. CommUtils.printDataJason(response, restfulResult);
  180. }*/
  181. /* private void registerShutdownHook
    (final GraphDatabaseService graphDB){
  182. //关闭寄存器
  183. Runtime.getRuntime().addShutdownHook(new Thread(){
  184. public void run(){
  185. graphDB.shutdown();
  186. }
  187. });
  188. }*/
  189. }

我这里只是做了几个简单的Sample,调用方式如下:

(1) 创建节点(save)

(2) 删除节点(delete)

(3) 修改节点(update)

(4) 添加节点关系(relate)

(5) 自定义条件查询(search)

结果数据:

GitHub地址:https://github.com/sunroyi/neo4j.git

   
68 次浏览       4
相关文章

基于EA的数据库建模
数据流建模(EA指南)
“数据湖”:概念、特征、架构与案例
在线商城数据库系统设计 思路+效果
 
相关文档

Greenplum数据库基础培训
MySQL5.1性能优化方案
某电商数据中台架构实践
MySQL高扩展架构设计
相关课程

数据治理、数据架构及数据标准
MongoDB实战课程
并发、大容量、高性能数据库设计与优化
PostgreSQL数据库实战培训

最新活动计划
DeepSeek大模型应用开发 6-12[厦门]
人工智能.机器学习TensorFlow 6-30[直播]
基于 UML 和EA进行分析设计 6-23[北京]
嵌入式软件架构-高级实践 7-9[北京]
用户体验、易用性测试与评估 7-25[西安]
图数据库与知识图谱 8-23[北京]
 
 
最新文章
InfluxDB概念和基本操作
InfluxDB TSM存储引擎之数据写入
深度漫谈数据系统架构——Lambda architecture
Lambda架构实践
InfluxDB TSM存储引擎之数据读取
最新课程
Oracle数据库性能优化、架构设计和运行
并发、大容量、高性能数据库设计与优化
NoSQL数据库(原理、应用、最佳实践)
企业级Hadoop大数据处理最佳实践
Oracle数据库性能优化最佳实践
成功案例
某金融公司 Mysql集群与性能优化
北京 并发、大容量、高性能数据库设计
知名某信息通信公司 NoSQL缓存数据库
北京 oracle数据库SQL优化
中国移动 IaaS云平台-主流数据库及存储