1. 概述
Neo4j:是一个开源的 NoSQL 数据库,使用 scala 和 java 语言开发,是目前最流行的图数据库之一。
Neo4j优点:
- 使用灵活的查询语言Cypher,可以方便地查询和操作图形数据。
- 能够快速执行复杂查询。
- 支持集群部署。
- 支持 ACID 事务,能够确保数据的一致性、完整性和可靠性。
- 提供了多中语言的客户端库,如java、python、.NET等等。
- 拥有强大的社区支持,可以更加方便的学习和使用。
1.1 Neo4j的数据模型
节点:用于表达各种实体,如人、部门、物品等等。
属性:存储节点或关系的详细信息,以键值对的形式存在。
标签:用于区分节点,每个节点可以有多个标签。
关系:用于节点之间的连接,是图数据库的核心,每个关系都有方向,从一个节点指向另一个节点。
1.2 Neo4j的适用场景
- 社交网络
- 实时推荐系统
- 知识图谱
- 欺诈检测
- ...
2. 安装
官网地址:Neo4j Graph Database & Analytics | Graph Database Management System
准备工作:安装 JDK
版本对应:
- 3.x:JDK8
- 4.x:JDK11
- 5.x:JDK17
2.1 Windows
下载地址:Neo4j Deployment Center - Graph Database & Analytics
1. 下载
2. 解压
3. 启动(进入 bin 文件夹,打开 cmd)
4. 访问 http://localhost:7474/
默认账号:neo4j
默认密码:neo4j
2.2 Linux
下面以 CentOS 为例安装 Neo4j:
# 1.添加 Neo4j 仓库
sudo tee /etc/yum.repos.d/neo4j.repo <<EOF
[neo4j]
name=Neo4j Yum Repo
baseurl=http://yum.neo4j.org/stable
enabled=1
gpgcheck=1
EOF
# 2.导入密钥
sudo rpm --import https://debian.neo4j.com/neotechnology.gpg.key
# 3.安装Neo4j
sudo yum install neo4j-版本
# 4.启动 Neo4j 服务
sudo systemctl start neo4j
3. CQL
CQL:即Cypher Query Language,是 Neo4j 图形数据库的查询语言,是为处理图形数据而构建的。
常用命令 | 作用 |
create | 创建节点 |
match | 检索相关节点 |
return | 返回查询结果 |
where | 根据条件过滤检索数据 |
delete | 删除节点、关系 |
remove | 删除节点和关系的属性 |
order by | 对检索数据排序 |
set | 添加或更新属性 |
3.1 create命令
创建无属性节点:
create (node:label)
创建有属性节点:
create (
node:label
{
property1:value1,
property2:value2,
property3:value3,
...
}
)
创建多标签节点:
create (
node:label-1:label-2:...
{
property1:value1,
property2:value2,
property3:value3,
...
}
)
创建关系:
create (node1-:label)- [relationship:<relationship-label] ->(node2:label)
注意:节点之间的关系是有方向的。
3.2 match命令
语法:
match ( node:label )
3.3 return命令
不能够单独使用,常与 match 一起使用。
语法:
match (node:label)
return node.<property1>, ······ node.<propertyN>
3.4 where命令
不能单独使用,通常与 match、return 一起使用。
简单条件检索:
match (node:label)
where 条件
return node.<property1>, ······ node.<propertyN>
复杂条件检索:
match (node:label)
where 条件1 bool 条件2
return node.<property1>, ······ node.<propertyN>
bool的取值:
- AND:与
- OR:或
- NOT:非
- XOR:异或
3.5 delete命令
不能单独使用,通常与 match 一起使用。
删除节点:
match (xx:label) delete xx
删除节点及其关系:
match (n1:label)-[r]->(n2:label) delete n1,r,n2
3.6 remove命令
不能单独使用,通常与 match 一起使用。
删除节点或关系的属性:
match (node:label)
remove property1,property2,...,propertyN
删除节点或关系的标签:
match (node:label)
remove label1,label2,...,labelN
3.7 set命令
语法:
match (node:label)
where 条件
set node.property1 = value1,...,node.property2 = value2
3.8 order by命令
不能单独使用,通常与 match 一起使用。
按属性升序:
match (node:label)
return ...
order by node.property
按属性降序:
match (node:label)
return ...
order by node.property desc
3.9 merge 命令
merge:当前查询节点的属性存在,则不创建新的节点,如果属性不存在就创建新节点。
merge = match + create
语法:
merge (
node:label
{
property1:value1,
property2:value2,
property3:value3,
...
}
)
3.10 load cvs命令
load cvs:从 cvs 文件中导入数据。
准备工作:将 cvs 文件放入到 import 文件夹中。
参数:
参数 | 说明 |
with headers | 读取文件的第一行作为参数名 |
as line | 为每行数据重命名 |
fieldterminator ‘,’ | 自定义字段定界符为 , |
using periodic commit x | 每满 x 条提交一次,防止内存溢出,默认值 1000 |
举例:
load csv with headers
from 'file:///abc.csv'
as line
fieldterminator ','
create (
p:content
{
id: toInteger(line.id),
content: line.content
}
)
4. CQL函数
4.1 常用的String函数
函数 | 作用 |
upper(节点.属性) | 将字符串中的所有字母更改为大写字母 |
lower(节点.属性) | 将字符串中的所有字母更改为小写字母 |
substring(节点.属性,起始索引,结束索引) | 获取所给字符串的指定子字符串 |
replace(节点.属性,要替换的字符串,替换成的字符串) | 替换所给字符串的子字符串 |
4.2 聚合函数
函数 | 作用 |
count(*) | 统计 match 命令返回的行数 |
max(节点.属性) | 找到 match 命令返回的一组数据中的最大值 |
min(节点.属性) | 找到 match 命令返回的一组数据中的最小值 |
sum(节点.属性) | 统计 match 命令返回的一组数据的值求和 |
avg(节点.属性) | 统计 match 命令返回的一组数据的值求平均值 |
4.3 关系函数
函数 | 作用 |
startnode(关系) | 获取关系的开始节点 |
endnode(关系) | 获取关系的结束节点 |
id(关系) | 获取关系的id |
type(关系) | 获取关系的类型信息 |
5. SpringBoot整合Neo4j
5.1 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Neo4j依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
5.2 创建实体
注解说明:
- @Node:标明是一个实体。
- @Id:实体主键。
- @GeneratedValue:实体属性值自增。
- @Property:实体属性。
- @Relationship:声明实体之间关系。
实例:
@Data
@Node(labels = {"NBAathletes"}) // 声明实体,并指定标签名
public class NBAathlete implements Serializable {
@Id
@GeneratedValue
private Long id; // 声明主键
@Property
private String name; // 声明 name 属性
@Property
private String height; // 声明 height 属性
@Property
private String weight; // 声明 weighr 属性
@Property
private int num; // 声明 num 属性
@Property
private String role; // 声明 role 属性
@Relationship(type = "TeamMate",direction = Relationship.Direction.OUTGOING)
// 声明关系属性 TeamMate,指定关系方向
private List<NBAathlete> teamMate = new ArrayList<>();
@Override
public String toString() {
return "NBAathlete{" +
"id=" + id +
", teamMateCount=" + (teamMate != null ? teamMate.size() : 0) +
'}';
}
}
5.3 创建接口
/*
1.继承 Neo4jRepository 接口。
2.指定实体 NBAathlete
3.指定ID类型为 Long
*/
@Repository
public interface NBAathleteRepository extends Neo4jRepository<NBAathlete,Long> {
}
5.4 功能——查询
@SpringBootTest
class Neo4jDemoApplicationTests {
@Autowired
NBAathleteRepository nbAathleteRepository;
@Test
void findByID() {
Optional<NBAathlete> athleteOptional = nbaAthleteRepository.findById(3L);
NBAathlete athlete = athleteOptional.get();
}
@Test
void findAll() {
List<NBAathlete> allAthlete = nbaAthleteRepository.findAll();
}
}
5.5 功能——添加
@SpringBootTest
class Neo4jDemoApplicationTests {
@Autowired
NBAathleteRepository nbAathleteRepository;
@Test
void add() {
// 配置实体信息
NBAathlete athlete = new NBAathlete();
athlete.setHeight("196cm");
athlete.setWeight("86kg");
athlete.setRole("后卫");
athlete.setNum(10);
athlete.setName("xx-aa");
// 保存
nbaAthleteRepository.save(athlete);
}
}
5.6 功能——删除
@SpringBootTest
class Neo4jDemoApplicationTests {
@Autowired
NBAathleteRepository nbAathleteRepository;
@Test
void delete() {
NBAathlete athlete_1 = new NBAathlete();
athlete_1.setId(34L);
nbaAthleteRepository.delete(athlete_1);
}
@Test
void deleteById() {
nbaAthleteRepository.deleteById(34L);
}
@Test
void deleteAll() {
nbaAthleteRepository.deleteAll();
}
}
5.7 功能——添加关系
@SpringBootTest
class Neo4jDemoApplicationTests {
@Autowired
NBAathleteRepository nbAathleteRepository;
@Test
void addRelationShip() {
// 查找
Optional<NBAathlete> athlete_1 = nbaAthleteRepository.findById(0L);
Optional<NBAathlete> athlete_2 = nbaAthleteRepository.findById(35L);
NBAathlete n1 = athlete_1.get();
NBAathlete n2 = athlete_2.get();
// 添加关系
n1.getTeamMate().add(n2);
// 保存
nbaAthleteRepository.save(n1);
}
}