Neo4j graph database

Table of contents

Neo4j Basics

What is Neo4j

Neo4j Module Construction

The main application scenarios of Neo4j

Neo4j environment construction

Docker install Neo4j

Neo4j Data Browser

 Neo4j CQL

Introduction to CQL

Neo4j CQL Advanced

CQL function

CQL multi-depth relationship node

affairs

index

constraint

Admin administrator operation of Neo4j

Neo4j - database backup and restore

Tuning ideas

 Neo4j program access

SpringBoot integrates Neo4j


Neo4j Basics

What is Neo4j

Neo4j is an open source Shcema-free graph database developed based on java, which stores structured data in graphs instead of tables. It is an embedded, disk-based Java persistence engine with full transactional features. Program data is in an object-oriented, flexible network structure, rather than strict, static tables, but can enjoy all the benefits of a fully transactional, enterprise-level database.

https://db-engines.com/en/ranking

Neo4j Module Construction

Neo4j main building blocks

  • node
  • Attributes
  • relation
  • Label
  • data browser

node

A node is the basic unit of a graph. It contains properties with key-value pairs

Attributes

Properties are key-value pairs used to describe graph nodes and relationships

Key = value

where Key is a string

Values ​​can be represented by using any Neo4j data type

relation

Relations are another major building block of graph databases. It connects two nodes as shown below.

 Here Emp and Dept are two different nodes. "WORKS_FOR" is the relationship between Emp and Dept nodes.

Since it represents the arrow marker from Emp to Dept, then the relationship describes the same

Emp WORKS_FOR Dept

Each relationship contains a start node and an end node.

Here "Emp" is a start node.

"Dept" is the end node.

Since this relationship arrow mark represents a relationship from the "Emp" node to the "Dept" node, this relationship is called an "entry relationship" to the "Dept" node.

And an "outward relationship" to the "Emp" node.

Like nodes, relationships can also contain attributes as key-value pairs.

Label

Label associates a common name with a set of nodes or relationships. A node or relationship can contain one or more labels. we can now

Create new tags with nodes or relationships. We can remove existing labels from existing nodes or relationships.

From the previous figure, we can observe that there are two nodes.

The nodes on the left each have a label: "EMP", and the nodes on the right have a label: "Dept".

The relationship between these two nodes also has a label: "WORKS_FOR"

Note : - Neo4j stores data in properties of nodes or relationships.

The main application scenarios of Neo4j

social media and social networking

When using a graph database to power a social networking application, it is easy to exploit social relationships or infer relationships based on activity.

Query community cluster analysis, friend-of-friend recommendation, influencer analysis, sharing and collaboration relationship analysis, etc.

Recommendation Engines and Product Recommendation Systems

Graph-driven recommendation engines help companies personalize products, content and services by leveraging multiple connections in real time.

Content and media recommendations, graphic-assisted search engines, product recommendations, professional networking, social recommendations.

Identity and Access Management

Track users, assets, relationships, and authorizations quickly and efficiently when using a graph database for identity and access management.

Query access management, asset provenance, data ownership, identity management, interconnected organizations, master data, resource authorization

Financial anti-fraud multi-dimensional correlation analysis scenario

Through graph analysis, we can clearly know the money laundering network and related suspicions, such as performing correlation analysis on the account number used by the user, the IP address, MAC address, and mobile phone IMEI number when the transaction occurred.

Neo4j environment construction

Build under Linux in Neo4j environment

(1). Switch to Linux and go to the installation directory neo4j to upload the installation package or download the installation package

Use the ftp tool to upload neo4j-community-3.5.17.tar to liunx

or wget https://neo4j.com/artifact.php?name=neo4j-community-3.5.17-unix.tar.gz

(2). Unzip

tar -xvf neo4j-community-3.5.17.tar

(3). Modify the configuration file neo4j.conf

vi conf/neo4j.conf

The main thing is to modify the address that allows remote access and open the corresponding comment

dbms.connectors.default_listen_address=0.0.0.0

(4). Open the corresponding access port to open 7474 and 7687 by default

fifirewall-cmd --zone=public --add-port=7474/tcp --permanent

fifirewall-cmd --zone=public --add-port=7687/tcp --permanent

systemctl reload fifirewalld

(5).Start

./bin/neo4j start

(6). Use a browser to access neo4j on the server

http://192.168.8.128:7474

The default account is neo4j password neo4j If you log in for the first time here, you will be asked to change the password

Docker install Neo4j

1. Pull the Neo4j image

docker pull neo4j

2. Simply run Neo4j

docker run -d --name neo4j  -p 7474:7474 -p 7687:7687  neo4j

3. Check the log to see if the startup is successful

docker logs -f neo4j 

4. Visit the data browser to check whether it is successful

http://192.168.8.128:7474/browser

To mount a directory:

  • data - the folder where the data is stored
  • logs - run log folder
  • conf——database configuration folder (configuration in the configuration file neo4j.conf includes opening remote connections and setting the default activated database)
  • import——In order to import csv in large quantities to build a database, the node file nodes.csv and the relationship file rel.csv that need to be imported need to be placed in this folder)
docker run -d --name container_name \  //-d表示容器后台运行 --name指定容器名字
	-p 7474:7474 -p 7687:7687 \  //映射容器的端口号到宿主机的端口号
	-v /home/neo4j/data:/data \  //把容器内的数据目录挂载到宿主机的对应目录下
	-v /home/neo4j/logs:/logs \  //挂载日志目录
	-v /home/neo4j/conf:/var/lib/neo4j/conf   //挂载配置目录
	-v /home/neo4j/import:/var/lib/neo4j/import \  //挂载数据导入目录
	--env NEO4J_AUTH=neo4j/password \  //设定数据库的名字的访问密码
	neo4j //指定使用的镜像

Neo4j Data Browser

Data browser access

Once we have Neo4j installed, we can access the Neo4j Data Browser using the following URL

http:// localhost:7474/browser/

 Neo4j Data Browser is used to execute CQL commands and view the output.

Here we need to execute all CQL commands at the dollar prompt: "$" such as CREATE(cc:CreditCard), type the command after the dollar sign, and click the "Execute" button to run the command.

It interacts with the Neo4j database server to retrieve and display the results below to that $prompt.

Use the "VI View" button to view the results in graphical format. The image above shows the results in a "UI View" format.

Export CSV or JSON

Click the "Export CSV" button to export the results in csv file format

 Neo4j CQL

Introduction to CQL

CQL stands for Cypher Query Language. Like relational databases have a query language SQL, Neo4j uses CQL as a query language.

Neo4j CQL

  • It is the query language for the Neo4j graph database.
  • It is a declarative pattern matching language.
  • It follows SQL syntax.
  • Its syntax is very simple and in a human-readable format.

Commonly used Neo4j CQL commands/terms are as follows:

S.No. 

CQL command/bar 

effect

1

CREATE create 

Create nodes, relationships and attributes

2

MATCH match 

Retrieve data about nodes, relationships and attributes

3

RETURN Return

return query result
4

WHERE condition

Provide condition filtering to retrieve MATCH data
5

DELETE delete

Delete nodes and relationships
6

REMOVE remove

Delete attributes of nodes and relationships
7

SET settings

Add or update tags
8

ORDER BY sorting

Sort results
9

SKIP LIMIT tab

paging
10

DISTINCT deduplication

Heavy discharge

 CREATE

CREATE ( 

<node-name>:<label-name> 

[{ 

<property1-name>:<property1-Value> 

........ 

<propertyn-name>:<propertyn-Value> 

}] 

)

Grammar description:

grammatical element describe
< node-name> It is the node name we will create.
< label-name>  It is a node label name

< property1-name>...< propertyn-name>

Properties are key-value pairs. Defines the name of the property that will be assigned to the created node

< property1-value>...< propertyn-value> 

Properties are key-value pairs. Defines the value that will be assigned to the property of the created node

Example:

CREATE (person:Person {cid:1,name:"小张",age:24,gender:0,character:"A",money:1000}); 

MATCH RETURN command syntax 

MATCH 

<node-name>:<label-name> 

)

RETURN 

<node-name>.<property1-name>, 

... 

<node-name>.<propertyn-name>

grammatical element describe

< node-name> 

It is the node name we will create.

< label-name> 

 It is a node label name

< property1-name>...< propertyn-name>

Properties are key-value pairs. Defines the name of the property that will be assigned to the created node

Example:

MATCH (person:Person) return person 

MATCH (person:Person) return person.name,person.age 

relationship creation

  • Create relationship with no attributes using existing nodes

MATCH (<node1-name>:<node1-label-name>),(<node2-name>:<node2-label-name>) 

CREATE

(<node1-name>)-[<relationship-name>:<relationship-label-name>]->(<node2- 

name>) 

RETURN the corresponding content 

Grammar description:

S.No.  grammatical element describe
1 MATCH,CREATE,RETURN  They are Neo4J CQL keywords.
2 < noode1-name>  It is used to create the name of the "From Node" of the relationship.
3 < node1-label-name>  It is used to create the label name of the "From Node" of the relationship.
4 < node2-name>  It is used to create the name of the "To Node" of the relationship.
5 < node2-label-name>  It is used to create the label name of the "To Node" of the relationship.
6 < relationship-name>  This is the name of a relationship.
7 < relationship-label-name>  It is the label name of a relation.

Example:

create relationship 

match(person:Person {name:"小张"}) ,(person2:Person {name:"小林"}) create(person)-[r:Couple]->(person2); 

query relationship 

match p = (person:Person {name:"小张"})-[r:Couple]->(person2:Person) return p 

match (p1:Person {name:"Xiao Zhang"})-[r:Couple]-(p2:Person) return p1,p2 

match (p1:Person {name:"小张"})-[r:Couple]-(p2:Person) return r

  • Create a relationship with attributes using existing nodes

MATCH (<node1-label-name>:<node1-name>),(<node2-label-name>:<node2-name>) 

CREATE

(<node1-label-name>)-[<relationship-label-name>:<relationship-name> 

{<define-properties-list>}]->(<node2-label-name>) 

RETURN <relationship-label-name> 

where <define-properties-list> is a list of properties (name-value pairs) to assign to the newly created relationship. 

<property1-name>:<property1-value>, 

<property2-name>:<property2-value>, 

... 

<propertyn-name>:<propertyn-value> 

}

Example:

match(person:Person {name:"Xiao Zhang"}),(person2:Person {name:"Xiao Lin"}) 

create(person)-[r:Couple{mary_date:"12/12/2014",price:55000}]->(person2) 

return r; 

  • Create a relationship with no attributes using a new node

CREATE 

(<node1-label-name>:<node1-name>) 

-[<relationship-label-name>:<relationship-name>]-> 

(<node1-label-name>:<node1-name>) 

Example:

create

(person1:Person {cid:4,name:"小王",age:49,gender:1,character:"A",money:5000}) 

-[r:Friend]-> 

(person2:Person{cid:7,name:"小刘",age:48,gender:0,character:"B",money:100}) 

  • Create a relationship with attributes using a new node

CREATE 

(<node1-label-name>:<node1-name>{<define-properties-list>}) 

-[<relationship-label-name>:<relationship-name>{<define-properties-list>}] 

->(<node1-label-name>:<node1-name>{<define-properties-list>}) 

Example:

create

(person1:Person {cid:9,name:"王武",age:23,gender:0,character:"A",money:3000}) 

<-[r:Friend {date:"11-02-2000"}]-> 

(person2:Person {cid:8,name:"赵六",age:24,gender:0,character:"B",money:6000})

The types that properties of relationships and nodes can use

Index CQL data types effect
1 boolean  It is used to represent Boolean literals: true, false.
2 byte  It is used to represent 8-bit integers.
3 short  It is used to represent 16-bit integers.
4 int  It is used to represent 32 bit integer
5 Long  It is used to represent 64-bit integers.
6 float  Floats are used to represent 32-bit floating point numbers.
7 double Double is used to represent 64-bit floating point numbers.
8 char Char is used to represent 16-bit characters.
9 String  String is used to represent strings.

CREATE creates multiple tags

CREATE (<node-name>:<label-name1>:<label-name2>.....:<label-namen>) 

like: 

CREATE (person:Person:Beauty:Picture {cid:20,name:"小美女"}) 

WHERE 子句

简单的WHERE子句 

WHERE <condition> 

复杂的WHERE子句 

WHERE <condition> <boolean-operator> <condition> 

where 中的比较运算符 和 之前mysql的相同 如 = != <> > < 等

S.No.  布尔运算符 描述
1 AND  与 
2 OR  或 
3 NOT 

举例:

MATCH (person:Person) 

WHERE person.name = '小张' OR person.name = '小王' 

RETURN person

DELETE 子句 和 REMOVE子句

DELETE 子句

  • 删除节点。
  • 删除节点及相关节点和关系。

match p = (:Person {name:"小王"})-[r:Couple]-(:Person) delete r 

REMOVE子句

  • 删除节点或关系的标签
  • 删除节点或关系的属性

MATCH (person:Person {name:"小美女"})  REMOVE person.cid 

SET子句

  • 向现有节点或关系添加新属性
  • 更新属性值

MATCH (person:Person {cid:1}) 

SET person.money = 3456,person.age=25 

ORDER BY 子句

“ORDER BY”子句,对MATCH查询返回的结果进行排序。

我们可以按升序或降序对行进行排序。

默认情况下,它按升序对行进行排序。 如果我们要按降序对它们进行排序,我们需要使用DESC子句。

MATCH (person:Person) 

RETURN person.name,person.money 

ORDER BY person.money DESC 

SKIP 和 LIMIT

Neo4j CQL已提供“SKIP”子句来过滤或限制查询返回的行数。 它修整了CQL查询结果集顶部的结果。

Neo4j CQL已提供“LIMIT”子句来过滤或限制查询返回的行数。 它修剪CQL查询结果集底部的结果。

MATCH (person:Person) 

RETURN ID(person),person.name,person.money 

ORDER BY person.money DESC skip 4 limit 2

DISTINCT 排重

这个函数的用法就像SQL中的distinct关键字,返回的是所有不同值。

MATCH (p:Person) RETURN Distinct(p.character) 

Neo4j CQL高级

CQL 函数

字符串函数

S.No.  功能 描述
1 UPPER  它用于将所有字母更改为大写字母。
2 LOWER  它用于将所有字母改为小写字母。
3 SUBSTRING  它用于获取给定String的子字符串。
4 REPLACE  它用于替换一个字符串的子字符串。

举例:

MATCH (p:Person) 

RETURN ID(p),LOWER(p.character) 

match(p:Person) return 

p.character,lower(p.character),p.name,substring(p.name,2),replace(p.name,"子","zi") 

聚合函数

S.No.  聚集功能 描述
1 COUNT  它返回由MATCH命令返回的行数。
2 MAX  它从MATCH命令返回的一组行返回最大值。
3 MIN  它返回由MATCH命令返回的一组行的最小值。
4 SUM  它返回由MATCH命令返回的所有行的求和值。
5 AVG  它返回由MATCH命令返回的所有行的平均值。

举例:

MATCH (p:Person) 

RETURN MAX(p.money),SUM(p.money)

关系函数

S.No.  聚集功能 描述
1 STARTNODE  它用于知道关系的开始节点。
2 ENDNODE  它用于知道关系的结束节点。
3 ID  它用于知道关系的ID
4 TYPE  它用于知道字符串表示中的一个关系的TYPE。

举例:

match p = (:Person {name:"小王"})-[r:Couple]-(:Person) 

RETURN STARTNODE(r) 

shortestPath 函数返回最短的path

MATCH p=shortestPath( (node1)-[*]-(node2) ) 

RETURN length(p), nodes(p) 

举例:

MATCH p=shortestPath((person:Person {name:"小王"})-[*]-(person2:Person 

{name:"王武"}) ) RETURN length(p), nodes(p)

CQL多深度关系节点

使用with关键字

查询三层级关系节点如下:with可以将前面查询结果作为后面查询条件

match (na:Person)-[re]->(nb:Person) where na.name="小张" WITH na,re,nb match (nb:Person)-[re2]->(nc:Person) return na,re,nb,re2,nc

match (na:Person)-[re]->(nb:Person) where na.name="小林" WITH na,re,nb match (nb:Person)-[re2]->(nc:Person) return na,re,nb,re2,nc

直接拼接关系节点查询

match (na:Person{name:"小张"})-[re]->(nb:Person)-[re2]->(nc:Person) return na,re,nb,re2,nc

为了方便,可以将查询结果赋给变量,然后返回

match data=(na:Person{name:"小张"})-[re]->(nb:Person)-[re2]->(nc:Person) return data

使用深度运算符

当实现多深度关系节点查询时,显然使用以上方式比较繁琐。

可变数量的关系->节点可以使用-[:TYPE*minHops..maxHops]-。

查询:

match data=(na:Person{name:"小张"})-[*1..2]-(nb:Person) return data

事务

为了保持数据的完整性和保证良好的事务行为,Neo4j也支持ACID特性 。

注意: 

(1)所有对Neo4j数据库的数据修改操作都必须封装在事务里。 

(2)默认的isolation level是READ_COMMITTED。 

(3)死锁保护已经内置到核心事务管理 。 (Neo4j会在死锁发生之前检测死锁并抛出异常。在异常抛出之前,事务会被标志为回滚。当事务结束时,事务会释放它所持有的锁,则该事务的锁所引起的死锁也就是解除,其他事务就可以继续执行。当用户需要时,抛出异常的事务可以尝试重新执行) 

(4)除特别说明,Neo4j的API的操作都是线程安全的,Neo4j数据库的操作也就没有必要使用外部的同步方法。

索引

简介

Neo4j CQL支持节点或关系属性上的索引,以提高应用程序的性能。

可以为具有相同标签名称的属性上创建索引。

可以在MATCH或WHERE等运算符上使用这些索引列来改进CQL 的执行。

创建单一索引

CREATE INDEX ON :Label(property)

例如:

CREATE INDEX ON :Person(name)

创建复合索引

CREATE INDEX ON :Person(age, gender)

全文模式索引

之前的常规模式索引只能对字符串进行精确匹配或者前后缀索(startswith,endswith,contains),全文索引将标记化索引字符串值,因此它可以匹配字符串中任何位置的术语。索引字符串如何被标记化并分解为术语,取决于配置全文模式索引的分析器。索引是通过属性来创建,便于快速查找节点或者关系。

创建和配置全文模式索引

使用db.index.fulltext.createNodeIndex和db.index.fulltext.createRelationshipIndex创建全文模式索引。在创建索引时,每个索引必须为每个索引指定一个唯一的名称,用于在查询或删除索引时引用相关的特定索引。然后,全文模式索引分别应用于标签列表或关系类型列表,分别用于节点和关系索引,然后应用于属性名称列表。

call db.index.fulltext.createNodeIndex("索引名",[Label,Label],[属性,属性]) 

call db.index.fulltext.createNodeIndex("nameAndDescription",["Person"],["name", 

"description"])

call db.index.fulltext.queryNodes("nameAndDescription", "小张") YIELD node, score 

RETURN node.name, node.description, score

查看和删除索引

call db.indexes 或者 :schema

DROP INDEX ON :Person(name)

DROP INDEX ON :Person(age, gender)

call db.index.fulltext.drop("nameAndDescription")

约束

唯一性约束

作用

  • 避免重复记录。
  • 强制执行数据完整性规则

创建唯一性约束

CREATE CONSTRAINT ON (变量:<label_name>) ASSERT 变量.<property_name> IS UNIQUE

具体实例:

CREATE CONSTRAINT ON (person:Person) ASSERT person.name IS UNIQUE

删除唯一性约束

DROP CONSTRAINT ON (cc:Person) ASSERT cc.name IS UNIQUE

3.5.2 属性存在约束 (企业版中可用) 

CREATE CONSTRAINT ON (p:Person) ASSERT exists(p.name)

查看约束

call db.constraints 

:schema

Neo4j之Admin管理员操作

Neo4j - 数据库备份和恢复

在对Neo4j数据进行备份、还原、迁移的操作时,首先要关闭neo4j

./bin/neo4j stop 

数据备份到文件

./bin/neo4j-admin dump --database=graph.db --to=/root/qyn.dump 

还原、迁移之前 ,关闭neo4j服务。操作同上

./bin/neo4j-admin load --from=/root/qyn.dump --database=graph.db --force 

重启服务

./bin/neo4j start 

注意,运行数据备份可能会警告

WARNING: Max 1024 open fifiles allowed, minimum of 40000 recommended. See the Neo4j

manual

1.编辑这个文件

vi /etc/security/limits.conf

在文件最后加入下面这段 修改最大打开文件限制

* soft nofile 65535 
* hard nofile 65535

2.重启服务器

再次执行上面的步骤 警告就没有了

调优思路

增加服务器内存 和 调整neo4j配置文件

# java heap 初始值 

dbms.memory.heap.initial_size=1g 

# java heap 最大值,一般不要超过可用物理内存的80% 

dbms.memory.heap.max_size=16g 

# pagecache大小,官方建议设为:(总内存-dbms.memory.heap.max_size)/2, 

dbms.memory.pagecache.size=2g 

neo4j刚启动数据是冷的需要预热

MATCH (n) 

OPTIONAL MATCH (n)-[r]->() 

RETURN count(n.name) + count(r);

查看执行计划进行索引优化

Cypher查询计划程序将每个查询转换为执行计划。 执行计划告诉Neo4j在执行查询时要执行哪些操作。

对执行计划的生成,Neo4j使用的都是基于成本的优化器(Cost Based Optimizer,CBO),用于制订精确的执行过程。可以采用如下两种不同的方式了解其内部的工作机制:

EXPLAIN:是解释机制,加入该关键字的Cypher语句可以预览执行的过程但并不实际执行,所以也不会产生任何结果。

PROFILE:则是画像机制,查询中使用该关键字,不仅能够看到执行计划的详细内容,也可以看到查询的执行结果。

关注指标: 

estimated rows: 需要被扫描行数的预估值 

dbhits: 实际运行结果的命中绩效 

两个值都是越小越好

使用索引和不使用索引对比

profile MATCH (p { name : '小张' }) RETURN p

在之前加上profile来进行查询,可以查看查询计划

 Neo4j 程序访问

SpringBoot 整合Neo4j

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.9</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zql</groupId>
    <artifactId>spring-boot-neo4j-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-neo4j-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.配置文件 application.yml

spring:
  data:
    neo4j:
      username: neo4j
      password: neo4j
      uri: bolt://localhost:7687

3.建立实体类

@Data
@ToString
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;
}

4.数据持久化类

@Repository
public interface PersonRepository extends Neo4jRepository<Person,Long> {

    @Query("MATCH (p:Person) where p.money > $money return p")
    List<Person> personList(@Param("money")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);

}

5.编写服务类

@Service
public class Neo4jPersonService {

    @Autowired
    private PersonRepository personRepository;

    public List<Person> personList(Double money){
        return personRepository.personList(money);
    }
    public List<Person> personAll(){
        return personRepository.findAll();
    }
    public Person save(Person person){
        return personRepository.save(person);
    }
    public List<Person> shortestPath(String startName, String endName){
        return personRepository.shortestPath(startName,endName);
    }
}

6.编写测试类

@SpringBootTest
class SpringBootNeo4jDemoApplicationTests {


    @Autowired
    private Neo4jPersonService neo4jPersonService;

    /**
     * 添加节点
     */
    @Test
    void save() {
        Person person = new Person();
        person.setAge(22);
        person.setName("小张");
        person.setGender(1);
        person.setMoney(10000);
        person.setGender(1);
        person.setDescription("描述");
        person.setCharacter("哈哈哈");
        person.setPid(2);
        Person person1 = neo4jPersonService.save(person);
        System.out.println(person1);
    }

    /**
     * 查询所有节点
     */
    @Test
    void selectAll() {
        List<Person> personList = neo4jPersonService.personAll();
        System.out.println(personList);
    }


    /**
     * 根据条件查询节点
     */
    @Test
    void condition() {
        List<Person> personList = neo4jPersonService.personList(new Double(1000));
        System.out.println(personList);
    }

    /**
     * 最短路径
     */
    @Test
    void shortestPath() {
        List<Person> personList = neo4jPersonService.shortestPath("小张", "王武");
        System.out.println(personList);
    }
    
}

Guess you like

Origin blog.csdn.net/xiaozhang_man/article/details/125582919