跨境互联网 跨境互联网
首页
  • AI 工具

    • 绘图提示词工具 (opens new window)
    • ChatGPT 指令 (opens new window)
  • ChatGPT

    • ChatGP T介绍
    • ChatGPT API 中文开发手册
    • ChatGPT 中文调教指南
    • ChatGPT 开源项目
  • Midjourney

    • Midjourney 文档
  • Stable Diffusion

    • Stable Diffusion 文档
  • 其他

    • AIGC 热门文章
    • 账号合租 (opens new window)
    • 有趣的网站
  • Vue

    • Vue3前置
  • JAVA基础

    • Stream
    • Git
    • Maven
    • 常用第三方类库
    • 性能调优工具
    • UML系统建模
    • 领域驱动设计
    • 敏捷开发
    • Java 测试
    • 代码规范及工具
    • Groovy 编程
  • 并发编程&多线程

    • 并发编程
    • 高性能队列 Disruptor
    • 多线程并发在电商系统下的应用
  • 其他

    • 面试题
  • 消息中间中间件

    • Kafka
    • RabbitMQ
    • RocketMQ
  • 任务调度

    • Quartz
    • XXL-Job
    • Elastic-Job
  • 源码解析

    • Mybatis 高级使用
    • Mybatis 源码剖析
    • Mybatis-Plus
    • Spring Data JPA
    • Spring 高级使用
    • Spring 源码剖析
    • SpringBoot 高级使用
    • SpringBoot 源码剖析
    • Jdk 解析
    • Tomcat 架构设计&源码剖析
    • Tomcat Web应用服务器
    • Zookeeper 高级
    • Netty
  • 微服务框架

    • 分布式原理
    • 分布式集群架构场景化解决方案
    • Dubbo 高级使用
    • Dubbo 核心源码剖析
    • Spring Cloud Gateway
    • Nacos 实战应用
    • Sentinel 实战应用
    • Seata 分布式事务
  • 数据结构和算法的深入应用
  • 存储

    • 图和Neo4j
    • MongoDB
    • TiDB
    • MySQL 优化
    • MySQL 平滑扩容实战
    • MySQL 海量数据存储与优化
    • Elasticsearch
  • 缓存

    • Redis
    • Aerospike
    • Guava Cache
    • Tair
  • 文件存储

    • 阿里云 OSS 云存储
    • FastDF 文件存储
  • 基础

    • Linux 使用
    • Nginx 使用与配置
    • OpenResty 使用
    • LVS+Keepalived 高可用部署
    • Jekins
  • 容器技术

    • Docker
    • K8S
    • K8S
  • 01.全链路(APM)
  • 02.电商终极搜索解决方案
  • 03.电商亿级数据库设计
  • 04.大屏实时计算
  • 05.分库分表的深入实战
  • 06.多维系统下单点登录
  • 07.多服务之间分布式事务
  • 08.业务幂等性技术架构体系
  • 09.高并发下的12306优化
  • 10.每秒100W请求的秒杀架构体系
  • 11.集中化日志管理平台的应用
  • 12.数据中台配置中心
  • 13.每天千万级订单的生成背后痛点及技术突破
  • 14.红包雨的架构设计及源码实现
  • 人工智能

    • Python 笔记
    • Python 工具库
    • 人工智能(AI) 笔记
    • 人工智能(AI) 项目笔记
  • 大数据

    • Flink流处理框架
  • 加密区

    • 机器学习(ML) (opens new window)
    • 深度学习(DL) (opens new window)
    • 自然语言处理(NLP) (opens new window)
AI 导航 (opens new window)

Revin

首页
  • AI 工具

    • 绘图提示词工具 (opens new window)
    • ChatGPT 指令 (opens new window)
  • ChatGPT

    • ChatGP T介绍
    • ChatGPT API 中文开发手册
    • ChatGPT 中文调教指南
    • ChatGPT 开源项目
  • Midjourney

    • Midjourney 文档
  • Stable Diffusion

    • Stable Diffusion 文档
  • 其他

    • AIGC 热门文章
    • 账号合租 (opens new window)
    • 有趣的网站
  • Vue

    • Vue3前置
  • JAVA基础

    • Stream
    • Git
    • Maven
    • 常用第三方类库
    • 性能调优工具
    • UML系统建模
    • 领域驱动设计
    • 敏捷开发
    • Java 测试
    • 代码规范及工具
    • Groovy 编程
  • 并发编程&多线程

    • 并发编程
    • 高性能队列 Disruptor
    • 多线程并发在电商系统下的应用
  • 其他

    • 面试题
  • 消息中间中间件

    • Kafka
    • RabbitMQ
    • RocketMQ
  • 任务调度

    • Quartz
    • XXL-Job
    • Elastic-Job
  • 源码解析

    • Mybatis 高级使用
    • Mybatis 源码剖析
    • Mybatis-Plus
    • Spring Data JPA
    • Spring 高级使用
    • Spring 源码剖析
    • SpringBoot 高级使用
    • SpringBoot 源码剖析
    • Jdk 解析
    • Tomcat 架构设计&源码剖析
    • Tomcat Web应用服务器
    • Zookeeper 高级
    • Netty
  • 微服务框架

    • 分布式原理
    • 分布式集群架构场景化解决方案
    • Dubbo 高级使用
    • Dubbo 核心源码剖析
    • Spring Cloud Gateway
    • Nacos 实战应用
    • Sentinel 实战应用
    • Seata 分布式事务
  • 数据结构和算法的深入应用
  • 存储

    • 图和Neo4j
    • MongoDB
    • TiDB
    • MySQL 优化
    • MySQL 平滑扩容实战
    • MySQL 海量数据存储与优化
    • Elasticsearch
  • 缓存

    • Redis
    • Aerospike
    • Guava Cache
    • Tair
  • 文件存储

    • 阿里云 OSS 云存储
    • FastDF 文件存储
  • 基础

    • Linux 使用
    • Nginx 使用与配置
    • OpenResty 使用
    • LVS+Keepalived 高可用部署
    • Jekins
  • 容器技术

    • Docker
    • K8S
    • K8S
  • 01.全链路(APM)
  • 02.电商终极搜索解决方案
  • 03.电商亿级数据库设计
  • 04.大屏实时计算
  • 05.分库分表的深入实战
  • 06.多维系统下单点登录
  • 07.多服务之间分布式事务
  • 08.业务幂等性技术架构体系
  • 09.高并发下的12306优化
  • 10.每秒100W请求的秒杀架构体系
  • 11.集中化日志管理平台的应用
  • 12.数据中台配置中心
  • 13.每天千万级订单的生成背后痛点及技术突破
  • 14.红包雨的架构设计及源码实现
  • 人工智能

    • Python 笔记
    • Python 工具库
    • 人工智能(AI) 笔记
    • 人工智能(AI) 项目笔记
  • 大数据

    • Flink流处理框架
  • 加密区

    • 机器学习(ML) (opens new window)
    • 深度学习(DL) (opens new window)
    • 自然语言处理(NLP) (opens new window)
AI 导航 (opens new window)
  • MySQL优化

  • MySQL海量数据存储与优化

  • 索引优化注意
  • MySQL平滑扩容实战
  • TiDB

  • 图和Neo4j

    • 1 图和 Neo4j 介绍
    • 2 Neo4j CQL
    • 3 Neo4j CQL高级
    • 3 Neo4j 之Admin管理员操作
    • 5 Neo4j 程序访问
      • 1 Neo4j 数据库访问
        • 1.1 Neo4j访问的两种方式
        • 1.2 An embedded database(嵌入式数据库)
        • 1.3 Neo4j Server(服务器模式)
      • 2 Java客户端操作Neo4j
        • 2.1 嵌入式模式
        • 2.2 服务器模式
      • 3 SpringBoot整合Neo4j
        • 3.1 导入jar包
        • 3.2 建立实体类
        • 3.3 数据持久化类
        • 3.4 配置文件application.yml
        • 3.5 编写服务类
        • 3.6 编写测试类
  • MongoDB

  • 缓存

  • 文件存储

  • Elasticsearch

  • 数据库与缓存
  • 图和Neo4j
Revin
2023-07-09
目录

5 Neo4j 程序访问

# 1 Neo4j 数据库访问

# 1.1 Neo4j访问的两种方式

  • 嵌入式数据库

  • 服务器模式(通过REST的访问)

它是由应用程序的性质(neo4j是独立服务器 还是和程序在一起),性能,监控和数据安全性来决定架构选择。

# 1.2 An embedded database(嵌入式数据库)

嵌入式Neo4j数据库是性能的最佳选择。 通过指定数据存储的路径以编程方式访问嵌入式数据库。

我们选择嵌入式数据库出于以下原因:

  • 使用Java作为我们项目的编程语言时

  • 应用程序是独立的

  • 程序追求很高的性能

# 1.3 Neo4j Server(服务器模式)

Neo4j Server是相互操作性,安全性和监控的最佳选择。 实际上,REST接口允许所有现代平台和编程语言与它进行互操作。 此外,作为独立应用程序,它比嵌入式配置更安全(客户端中的潜在故障不会影响服务器),并且更易于监控。 如果我们选择使用这种模式,我们的应用程序将充当Neo4j服务器的客户端。要连接到Neo4j服务器,可以使用任何编程语言的REST 访问数据库。

# 2 Java客户端操作Neo4j

# 2.1 嵌入式模式

<dependency>
	<groupId>org.neo4j</groupId>
	<artifactId>neo4j</artifactId>
	<version>3.5.5</version>
</dependency>
1
2
3
4
5
package com.lagou;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class EmbeddedNeo4jAdd
{
    private static final File databaseDirectory = new File("target/graph.db");
    public static void main(String[] args)
    {
        GraphDatabaseService graphDb = new
        GraphDatabaseFactory().newEmbeddedDatabase(databaseDirectory);
        System.out.println("Database Load!");
        Transaction tx = graphDb.beginTx();
        Node n1 = graphDb.createNode();
        n1.setProperty("name", "张三");
        n1.setProperty("character", "A");
        n1.setProperty("gender", 1);
        n1.setProperty("money", 1101);
        n1.addLabel(new Label()
        {
            @Override
            public String name()
            {
                return "Person";
            }
        });
        String cql = "CREATE (p:Person{name:'李
        四 ',character:'
        B ',gender:1,money:21000})";
        graphDb.execute(cql);
        tx.success();
        tx.close();
        System.out.println("Database Shutdown!");
        graphDb.shutdown();
    }
}
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
package com.lagou;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class EmbeddedNeo4jQueryAll
{
    private static final File databaseDirectory = new File("target/graph.db");
    public static void main(String[] args)
    {
        GraphDatabaseService graphDb = new
        GraphDatabaseFactory().newEmbeddedDatabase(databaseDirectory);
        System.out.println("Database Load!");
        String cql = "MATCH (a:Person) where a.money < $money return a";
        Map < String, Object > paramerters = new HashMap < String, Object > ();
        paramerters.put("money", 25000);
        Transaction tx = graphDb.beginTx();
        Result result = graphDb.execute(cql, paramerters);
        while(result.hasNext())
        {
            Map < String, Object > row = result.next();
            for(String key: result.columns())
            {
                Node nd = (Node) row.get(key);
                System.out.printf("%s = %s:%s%n", key, nd.getProperty("name"), nd.getProperty("money"));
            }
        }
        tx.success();
        tx.close();
        System.out.println("Database Shutdown!");
        graphDb.shutdown();
    }
}
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

# 2.2 服务器模式

<dependency>
	<groupId>org.neo4j</groupId>
	<artifactId>neo4j-ogm-bolt-driver</artifactId>
	<version>3.2.10</version>
</dependency>
1
2
3
4
5
package com.lagou;
import org.neo4j.driver.*;
import static org.neo4j.driver.Values.parameters;
public class Neo4jServerMain
{
    public static void main(String[] args)
    {
        Driver driver = GraphDatabase.driver("bolt://127.0.0.1:7687", AuthTokens.basic("neo4j", "123456"));
        Session session = driver.session();
        String cql = "MATCH (a:Person) WHERE a.money > $money " + "RETURN a.name AS name, a.money AS money order by a.money ";
        Result result = session.run(cql, parameters("money", 1000));
        while(result.hasNext())
        {
            Record record = result.next();
            System.out.println(record.get("name").asString() + " " + record.get("money").asDouble());
        }
        session.close();
        driver.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.lagou;
import org.neo4j.driver.*;
import static org.neo4j.driver.Values.parameters;
public class Neo4jServerMain2
{
    public static void main(String[] args)
    {
        Driver driver = GraphDatabase.driver("bolt://127.0.0.1:7687", AuthTokens.basic("neo4j", "123456"));
        Session session = driver.session();
        String cql = "MATCH p=shortestPath((person:Person {name:$startName})- [ * ] - (person2: Person
        {
            name: $endName
        })) RETURN p ";
    Result result = session.run(cql, parameters("startName", "王启
            年 ","
            endName ","
            九品射手燕小乙 ") );
            while(result.hasNext())
            {
                Record record = result.next();
                System.out.println(record);
            }
            session.close(); driver.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

# 3 SpringBoot整合Neo4j

Page25_01

# 3.1 导入jar包

<?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.lagou</groupId>
    <artifactId>neo4j_springboot_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-

8</project.reporting.outputEncoding>
        <java.version>1.11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-ogm-bolt-driver</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
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

# 3.2 建立实体类

package com.lagou.bean;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Property;
@NodeEntity
public class Person
{
    @Id
    @GeneratedValue
    private Long id;
    @Property("cid")
    private int pid;
    @Property
    private String name;
    private String character;
    private double money;
    private int gender;
    private int age;
    private String description;
    @Relationship(type = "Friends", direction = Relationship.INCOMING)
    private Set < Person > relationPersons;
    @Override
    public String toString()
    {
        return "Person{" + "id=" + id + ", pid=" + pid + ", name='" + name + '\'' + ", character='" + character + '\'' + ", money=" + money + ", gender=" + gender + ", age=" + age + ", description='" + description + '\'' + ", relationPersons=" + relationPersons + '}';
    }
    public Person()
    {}
    public Person(Long id, String name, String character, double money, int gender, int age, String description)
    {
        this.id = id;
        this.name = name;
        this.character = character;
        this.money = money;
        this.gender = gender;
        this.age = age;
        this.description = description;
    }
    public Set < Person > getRelationPersons()
    {
        return relationPersons;
    }
    public void setRelationPersons(Set < Person > relationPersons)
    {
        this.relationPersons = relationPersons;
    }
    public Long getId()
    {
        return id;
    }
    public void setId(Long id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getCharacter()
    {
        return character;
    }
    public void setCharacter(String character)
    {
        this.character = character;
    }
    public double getMoney()
    {
        return money;
    }
    public void setMoney(double money)
    {
        this.money = money;
    }
    public int isGender()
    {
        return gender;
    }
    public void setGender(int gender)
    {
        this.gender = gender;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public String getDescription()
    {
        return description;
    }
    public void setDescription(String description)
    {
        this.description = description;
    }
}
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

# 3.3 数据持久化类

package com.lagou.repository;
import com.lagou.bean.Person;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public interface PersonRepository extends Neo4jRepository < Person, Long >
{
    @Query("match(p:Person) where p.money > {0} return p")
    List < Person > personList(double money);
    @Query("MATCH p=shortestPath((person:Person {name:{0}})-[*1..4]-(person2: Person { name:{ 1}})) RETURN p ")
    List < Person > shortestPath(String startName, String endName);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

或者使用

@Query("match(p:Person) where p.money>{money} return p")
List<Person> personList(@Param("money") double money);

/** 指定开始的名字 和 结束的名字 查询最短路径 限定深度为4以层包含4*/
@Query("match p=shortestPath((person:Person{name:{startName}})-[*1..4]-(person2:Person {name:{endName}})) return p")
List<Person> shortestPath(@Param("startName") String startName,@Param("endName") String endName);
1
2
3
4
5
6

# 3.4 配置文件application.yml

spring:
	data:
		neo4j:
			username: neo4j
			password: 123456
			uri: bolt://192.168.211.133:7687
			#uri: http://192.168.211.133:7474
			#uri: file:///target/graph.db
1
2
3
4
5
6
7
8

# 3.5 编写服务类

package com.lagou.service;
import com.lagou.bean.Person;
import com.lagou.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class Neo4jPersonService
{
    @Autowired
    private PersonRepository personRepository;
    public List < Person > personList()
    {
        return personRepository.personList();
    }
    public Person save(Person person)
    {
        return personRepository.save(person);
    }
    public List < Person > shortestPath(String startName, String endName)
    {
        return personRepository.shortestPath(startName, endName);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 3.6 编写测试类

package com.lagou;
import com.lagou.bean.Person;
import com.lagou.service.Neo4jPersonService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.List;
@SpringBootApplication
public class TestNeo4jBootApp
{
    public static void main(String[] args){
            ApplicationContext app = SpringApplication.run(TestNeo4jBootApp.class, args);
            Neo4jPersonService personService = app.getBean(Neo4jPersonService.class);
            System.out.println(personService);
            List < Person > datas = personService.personListAll();
            System.out.println(datas);
            System.out.println(personService.shortestPath("王启年", "九品射手燕小乙 "));
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2025/04/03, 11:07:08
3 Neo4j 之Admin管理员操作
1 MongoDB基本使用

← 3 Neo4j 之Admin管理员操作 1 MongoDB基本使用→

最近更新
01
tailwindcss
03-26
02
PaddleSpeech
02-18
03
whisper
02-18
更多文章>
Theme by Vdoing | Copyright © 2019-2025 跨境互联网 | 豫ICP备14016603号-5 | 豫公网安备41090002410995号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式