springBoot 整合 neo4j

springBoot 整合 neo4j

坐标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.po</groupId>
    <artifactId>po-neo4j</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId><!--配合spring cloud版本 -->
        <version>2.5.6</version>
        <relativePath></relativePath>
    </parent>
 
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <neo4j.version>4.4.9</neo4j.version>
        <lombok.version>1.18.12</lombok.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver</artifactId>
            <version>${neo4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver</artifactId>
            <version>${neo4j.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
 
    </dependencies>
 
</project>

 spring配置文件(application.properties 和 application-dev.properties)

1
2
3
4
5
spring:
  application:
    name: poneo4j
  profiles:
    active: dev
1
2
3
4
5
6
7
8
9
10
server:
  port: 8899
  servlet:
    context-path: /poneo4j
spring:
  neo4j:
      #url: bolt://172.16.32.135:7687  #3.x
      url: neo4j://localhost:7687 #4.x
      username: neo4j
      password: 123456

 启动类

复制代码
package com.neo4j;
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
//启动springboot public class Neo4jApplication { private static Logger logger = LoggerFactory.getLogger(Neo4jApplication.class); public static void main(String[] args) throws Exception { SpringApplication.run(Neo4jApplication.class, args); logger.info("=======================Neo4jApplication=============启动成功"); } }
复制代码

neo4j配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.neo4j.config;
 
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
 
@Configuration
@ConfigurationProperties(prefix = "spring.neo4j") //指明配置节点
public class Neo4jConfig {
    @Value("${spring.neo4j.url}")
    private String url;
 
    @Value("${spring.neo4j.username}")
    private String username;
 
    @Value("${spring.neo4j.password}")
    private String password;
 
    /**
     * 图数据库驱动模式
     */
 
    @Bean
    public Driver neo4jDriver() {
        return GraphDatabase.driver(url, AuthTokens.basic(username, password));
    }
 
}

neo4j工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package com.neo4j.utils;
 
import org.neo4j.driver.*;
import org.neo4j.driver.types.Node;
import org.neo4j.driver.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
 
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
 
@Component
@Lazy(false)
public class Neo4jUtil implements AutoCloseable {
 
    private static Driver neo4jDriver;
 
    private static final Logger log = LoggerFactory.getLogger(Neo4jUtil.class);
 
    @Autowired
    @Lazy
    public void setNeo4jDriver(Driver neo4jDriver) {
        Neo4jUtil.neo4jDriver = neo4jDriver;
    }
 
    /**
     * 测试neo4j连接是否打开
     */
    public static boolean isNeo4jOpen() {
        try (Session session = neo4jDriver.session()) {
            log.debug("连接成功:" + session.isOpen());
            return session.isOpen();
        }
    }
 
 
    /**
     * 执行SQL语句 包含添加 删除
     * @param cypherSql
     */
    public static void executeCyphersCypherSql(String cypherSql) {
        try (Session session = neo4jDriver.session()) {
            log.debug(cypherSql);
            session.run(cypherSql);
        }
    }
 
    public <T> List<T> readCyphers(String cypherSql, Function<Record, T> mapper) {
        try (Session session = neo4jDriver.session()) {
            log.debug(cypherSql);
            Result result = session.run(cypherSql);
            return result.list(mapper);
        }
    }
 
    /**
     * 返回节点集合
     *
     * @param cypherSql cypherSql
     */
    public static List<HashMap<String, Object>> getGraphNode(String cypherSql) {
        List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
        try (Session session = neo4jDriver.session()) {
            log.debug(cypherSql);
            Result result = session.run(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) {
            log.error(e.getMessage());
        }
        return ents;
    }
 
    /**
     * 获取所有结点
     * @return
     */
    public static List<HashMap<String, Object>> getGraphLabels() {
        List<HashMap<String, Object>> ents = new ArrayList<HashMap<String, Object>>();
        try (Session session = neo4jDriver.session()) {
            String cypherSql="call db.labels";
            Result result = session.run(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 key = pair.key();
                        Value value = pair.value();
                        if(key.equalsIgnoreCase("label")){
                            String objects =value.toString().replace("\"","");
                            rss.put(key, objects);
                        }else{
                            rss.put(key, value);
                        }
                    }
                    ents.add(rss);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ents;
    }
 
 
    @Override
    public void close() throws Exception {
        neo4jDriver.close();
    }
}

 单元测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package com.po.neo4j;
 
import com.neo4j.Neo4jApplication;
import com.neo4j.utils.Neo4jUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import java.util.HashMap;
import java.util.List;
 
/**
 * 包名:com.dbs.test.mysql
 * 功能:TODO 对关键字进行提取
 * 作者:hualn
 * 日期:2018年1月18日 下午4:25:02
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Neo4jApplication.class)
public class Neo4jTest {
 
    /**
     * 查询节点
     */
    @Test
    public void selectLabels(){
        //查询所有节点
        List<HashMap<String, Object>> domains = Neo4jUtil.getGraphLabels();
        System.out.println(domains);
        //查询某个节点的所有数据
        String cypher="MATCH (p:Movie) RETURN p";
        List<HashMap<String, Object>> cypherResult = Neo4jUtil.getGraphNode(cypher);
        System.out.println(cypherResult);
    }
 
    /**
     * 新增单个节点
     */
    @Test
    public void addLabels(){
        //新增数据
        String cypherSql="MERGE (point:测点1 {title: '测点2',dataPointId: 'cedian1'})";
        Neo4jUtil.executeCyphersCypherSql(cypherSql);
    }
 
    /**
     * 删除节点和关系
     */
    @Test
    public void deleteLabel(){
        String cypherSql="match (n : TEST) delete n";
        Neo4jUtil.executeCyphersCypherSql(cypherSql);
    }
 
 
    /**
     * 新增两个节点 并 插入 之间的关系
     */
    @Test
    public void addLabelsAndRelations(){
        //先创建两个结点
        String cypherSql1="CREATE(n:TEST {name:'TEST-NAME', age:1})";
        Neo4jUtil.executeCyphersCypherSql(cypherSql1);
        String cypherSql2="CREATE(n:TEST {name:'TEST-NAME1', age:2}) ";
        Neo4jUtil.executeCyphersCypherSql(cypherSql2);
        //创建两个结点之间的关系
        StringBuilder sb=new StringBuilder();
        sb.append("MATCH (a:TEST),(b:TEST) ");
        sb.append("WHERE a.name = 'TEST-NAME' AND b.name = 'TEST-NAME1' ");
        sb.append("CREATE (a)-[r:CONTAINS {name:'包含'} ] -> (b) ");
        sb.append("RETURN r");
        Neo4jUtil.executeCyphersCypherSql(sb.toString());
    }
 
    /**
     * 删除节点和关系
     */
    @Test
    public void deleteLabelsAndRelations(){
        String cypherSql="MATCH (n:points)-[r]-() DELETE n,r";
        Neo4jUtil.executeCyphersCypherSql(cypherSql);
    }
 
    /**
     * 通过 属性 删除节点
     */
    @Test
    public void deleteLabelsProperty(){
        //type:'point',
        String cypherSql="MATCH (n:points {pointCode:'%s'} ) delete n ";
        cypherSql= String.format(cypherSql, "code1_2");
        Neo4jUtil.executeCyphersCypherSql(cypherSql);
    }
 
    /**
     * 通过 属性 删除节点
     */
    @Test
    public void deleteLabelsPropertyRelation(){
        //type:'point',
        String cypherSql="MATCH (n:points {type:'point',pointCode:'%s'} )-[r]-() DELETE n,r";
        cypherSql= String.format(cypherSql, "code1_2");
        Neo4jUtil.executeCyphersCypherSql(cypherSql);
    }
 
 
}

代码地址 :

链接: https://pan.baidu.com/s/1U0yPy6niT_0GQ5Ux4JdN_g?pwd=1234 提取码: 1234
--来自百度网盘超级会员v2的分享

 

posted @   __破  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示