[Neo4j database] Graph database_Neo4j adding nodes (relationships), query, and deletion operation analysis (Cypher statement)
Article directory
1 Introduction
Keywords in the Cypher language are not case-sensitive, but attribute values, labels, relation types, and variables are case-sensitive.
The concept of table does not exist in Neo4j, only labels (labels), nodes (Node), associations (Relation), paths (path), nodes stored in labels, nodes and associations can be simply understood as points, edges, and paths in the graph It is represented by nodes and associations, such as: (a)-[r]->(b), which means a path from node a to node b via association r.
In data query,
- Nodes are generally enclosed in parentheses ()
- Use parentheses [] in the relationship
2. Node creation and query
Note: When executing multiple cypher statements, separate the statements with semicolons. Under the settings menu in the browser, check Enable multi statement query editor, which is not selected by default.
2.1 Create a node
// 创建Person 标签,刘德华等若干节点,各自有name,birthday ,born,englishname等属性。
create (n:Person {
name: ‘刘德华’, birthday:‘1961年9月27日’,born: 1961 ,englishname:‘Andy Lau’})
create (n:Person {
name: ‘朱丽倩’, birthday:‘1966年4月6日’,born: 1966 ,englishname:‘Carol’}) ;
create (n:Person {
name: ‘刘向蕙’, birthday:‘2012年5月9日’,born: 2012 ,englishname:‘Hanna’}) ;
create (n:Person {
name: ‘任贤齐’, birthday:‘1966年6月23日’,born: 1966 ,englishname:‘Richie Jen’}) ;
create (n:Person {
name: ‘金城武’, birthday:‘1973年10月11日’,born: 1973,englishname:‘Takeshi Kaneshiro’}) ;
create (n:Person {
name: ‘林志玲’, birthday:‘1974年11月29日’,born: 1974,englishname:‘zhilin’}) ;
// 创建Movie 标签,彩云曲等若干节点,各自有title,released 等属性
create (n:Movie {
title: ‘彩云曲’,released: 1981})
create (n:Movie {
title: ‘神雕侠侣’,released: 1983})
create (n:Movie {
title: ‘暗战’,released: 2000})
create (n:Movie {
title: ‘拆弹专家’,released: 2017})
2.2 Query Node
// 查询整个图形数据库
match(n) return n;
// 查询具有指定标签的节点
match(n:Movie) return n;
// where 谓词查询
*根据name查询
match (n:Person) where n.name=‘林志玲’ return n
*根据节点的制定属性查询
match(n{
name:‘林志玲’}) return n;
// 根据节点属性的条件查询
match(n) where n.born<1967 return n;
3. Create relationships
The composition of the relationship: StartNode - [Variable:RelationshipType{Key1:Value1,Key2:Value2}] -> EndNode,
- When creating a relationship, the relationship type must be specified.
3.1 Create a relationship without any attributes
MATCH (a:Person),(b:Movie) WHERE a.name = ‘刘德华’ AND b.title = ‘暗战’ CREATE (a)-[r:DIRECTED]->(b) RETURN r;
// 查询关系
MATCH p=()-[r:DIRECTED]->() RETURN p LIMIT 25
3.2 Create a relationship and set the properties of the relationship
MATCH (a:Person),(b:Movie) WHERE a.name = ‘刘德华’ AND b.title = ‘神雕侠侣’ CREATE (a)-[r:出演 {
roles:[‘杨过’] }]->(b) RETURN r;
// 查询关系
MATCH p=()-[r:出演]->() RETURN p LIMIT 25
3.3 Create a bidirectional relationship
// 刘德华的女是刘向蕙,刘向蕙的父亲是刘德华
MATCH (a:Person),(c:Person)
WHERE a.name = ‘刘德华’ AND c.name = ‘刘向蕙’
CREATE (a)-[r:父亲 {
nickname:‘甜心’ }]->(c), (c)-[d:女儿 {
nickname:‘爹地’ }]->(a)
RETURN r;
Then, query:
MATCH p=()-[r:父亲]->() RETURN p LIMIT 25
//关系建错了,删除后重新建立
match(a:Person)-[r:女儿]- >(b:Person)delete r;
match(a:Person)-[r:父亲]- >(b:Person)delete r
//重新建立双向关系
MATCH (a:Person),(c:Person)
WHERE a.name = ‘刘德华’ AND c.name = ‘刘向蕙’
CREATE (a)-[r:父亲 {
nickname:‘爹地’ }]->(c), (c)-[d:女儿 {
nickname:‘甜心’ }]->(a)
RETURN r;
Next, look at the relationship:
match p=()-[r:父亲]- >() return p limit 2
Then, create a few more relationships
MATCH (a:Person),(c:Movie)
WHERE a.name = ‘刘德华’ AND c.title = ‘彩云曲’
CREATE (a)-[r:出演 {
partner:‘张国荣’ }]->(c), (c)-[d:演员 {
rolename:‘阿华哥’ }]->(a)
RETURN r;
MATCH (a:Person),(c:Movie)
WHERE a.name = ‘刘德华’ AND c.title = ‘拆弹专家’
CREATE (a)-[r:出演 {
partner:‘赵薇,高圆圆’ }]->(c), (c)-[d:演员 {
rolename:‘华仔’ }]->(a)
RETURN r;
MATCH (a:Person),(c:Movie)
WHERE a.name = ‘刘德华’ AND c.title = ‘神雕侠侣’
CREATE (a)-[r:出演 {
partner:‘刘亦菲’ }]->(c), (c)-[d:演员 {
rolename:‘杨过’ }]->(a)
RETURN r;
continue to add relationship
MATCH (a:Person),(c:Person)
WHERE a.name = ‘刘德华’ AND c.name = ‘任贤齐’
CREATE (a)-[d:朋友 {
sex:‘男’ }]->(c)
RETURN d;
MATCH (a:Person),(c:Person)
WHERE a.name = ‘刘德华’ AND c.name = ‘金城武’
CREATE (a)-[d:朋友 {
sex:‘男’ }]->(c)
RETURN d;
//这里没有给关系设置属性sex
MATCH (a:Person),(c:Person)
WHERE a.name = ‘刘德华’ AND c.name = ‘林志玲’
CREATE (a)-[d:朋友]->(c)
RETURN d;
Query the Person relationship:
MATCH (n:Person) RETURN n
3.4 Query relationship
- In Cypher, there are three types of relationships: the symbol "–" indicates a relationship, ignoring the type and direction of the relationship; the symbols "–>" and "<–" indicate a directional relationship;
// 查询整个数据图形
match(n) return n;
// 查询跟指定节点有关系的节点
match(n)–(m:Movie) return n
3.5 Query nodes with directed relationship
// 查询和刘德华有关系的电影
MATCH (:Person {
name: ‘刘德华’ })–>(movie)RETURN movie;
3.6 Naming the relationship
// 通过[r]为关系定义一个变量名,通过函数 type 获取关系的类型
MATCH (:Person {
name: ‘刘德华’ })-[r]->(movie) RETURN r,type(r);
3.7 Query specific relationship types
// 通过[Variable:RelationshipType{
Key:Value}]指定关系的类型和属性。
MATCH (:Person {
name: ‘刘德华’ })-[r:出演{
partner:‘张国荣’}]->(Movie) RETURN r,type(r);
// 查询和刘德华和张国荣合作过的电影
MATCH (:Person {
name: ‘刘德华’ })-[r:出演{
partner:‘张国荣’}]->(m:Movie) RETURN m;
// 查询被刘德华称呼为甜心的女儿
MATCH (:Person {
name: ‘刘德华’ })-[r:女儿{
nickname:‘甜心’}]->(m:Person) return m
// 查询刘德华的老婆是谁
Match (n:Person{
name: ‘刘德华’})-[:wife]->(a:Person) return a
// 查询刘德华出演过的电影
match(:Person{
name:‘l刘德华’})-[r:‘出演’]- >(a:Movie) return a
4. Delete (two methods)
4.1 Delete nodes directly from the command line
If the amount of data in the database is not large and the number of nodes is relatively small, we can delete nodes directly through the command line
1) Delete a node:
create (n:City {
name: ‘北京’})
Match (n:City{
name:‘北京’}) delete n
2) Delete relationship
Match (a:Person{
name:‘刘德华’})-[r:父亲]->(b:Person{
name:‘刘向蕙’}) delete r
Match (a:Person{
name:‘刘向蕙’})-[r:女儿]->(b:Person{
name:‘刘德华’}) delete r
3) Delete the corresponding node and all its relationships, that is, as long as the node that meets the key-value pair { property-name: value } condition will be deleted
match (n {
<property-name>:<value>} ) detach delete (n)
// 示例:
//创建节点
merge(t:Test{
id:01,name:"hh"})
merge(t:test{
id:02,name:"hh"})
//name为hh的两个节点及其关系都会删除
match (n{
name:"hh"}) detach delete (n)
4) Delete all nodes and all relationships
This command directly deletes all nodes and relationships in the database without filtering conditions
match (n) detach delete (n)
4.2 Delete database files
If the amount of data in the database is large and the number of nodes is very large, deleting through the command line will be slow, then we can directly delete the database through physical means.
- Such operations directly delete the database, and the data is of course cleared
method:
- First, we need to close the Neo4j database;
- Then find the storage directory of the Neo4j database, which is <NEO4J_HOME>/data/. If you forget NEO4J_HOME, you can check it in the environment variable
. Finally, perform different deletion operations for different neo4j versions.- Version 3.x: Neo4j version 3.x has a databases folder, enter this folder, there is a graph.db folder and a store_lock file.
This graph.db folder is the database we are currently using, just delete it directly. - Version 4.x: Neo4j version 4.x has a databases folder and a transactions folder, and graph.db exists in both folders.
We can delete the graph.db under these two folders.
- Version 3.x: Neo4j version 3.x has a databases folder, enter this folder, there is a graph.db folder and a store_lock file.
5. Common query keywords
5.1 count
Query how many people there are in Person
Match (n:Person ) return count(n)
Query the number of nodes (persons) with born=1966 in the label (Person):
三种写法(第三种不能用似乎):
1、Match (n:Person) where n.born=1966 return count(n)
2、Match (n:Person{
born:1966}) return count(n) //特别注意类型,如果存的类似是数字类型,使用字符串就查不出来
3. Match (n:Person) return count(n.born=1966) //貌似无效,查出来是错的?
5.2 limit
Match (n:Person) return n limit 3
5.3 Distinct
Two 1966s, only one shown:
Match (n:Person) return distinct(n.born)
5.4 Order by
Match(n:Person) return n order by n.born (默认升序)
Match(n:Person) return n order by n.born asc (升序)
Match(n:Person) return n order by n.born desc (降序)
5.5 Find by id
match (n) where id(n)=548 return n
5.6 Usage of In
Match (n) where ID(n) IN[353,145,547] return n
Match (n) where ID(n) IN[145,175,353,547,548] return n
5.7 Exists
The node has a record of the attribute name:
Match (n) where exists(n.title) return n
5.8 With
Query the nodes whose name starts with 'Liu':
Match (n) where n.name starts with ‘刘’ return n
5.9 Contains
Query the nodes containing 'Heroes' in the title:
Match (n:Movie) where n.title Contains ‘侠侣’ return n
5.10 Union all (Union)
Find the union without deduplication (de-reuse Union, as alias):
Match(n:Person) where n.born=1966 return n.name as name
Union all
Match(n:Movie) where n.released=1983 return n.title as name
6. Supplement
6.1 Create a complete Path
CREATE p =(m:Person{
name:‘刘亦菲’,title:“演员” })-[:签约]->(neo)<-[:签约]-(n:Person {
name: ‘赵薇’,title:“投资人” })
RETURN p
6.2 Add an attribute to a node
- To get a node by its ID, Neo4j recommends using the where clause and the ID function.
match (n)
where id(n)=358
set n.name = ‘华谊兄弟’
return n;
6.3 Add labels to nodes
match (n)
where id(n)=358
set n:公司
return n;
6.4 Adding attributes to relationships
match (n)-[r]->(m)
where id(n)=357 and id(m)=358
set r.经纪人=‘程晨’
return n;
Then, let Andy Lau also sign a contract with Huayi Brothers
MATCH (a:Person),(c:公司)
WHERE a.name = ‘刘德华’ AND c.name = ‘华谊兄弟’
CREATE (a)-[d:签约 {
经纪人:‘刘得得’ }]->©
RETURN d;
6.5 MERGE
The Merge clause has two functions:
- When the pattern (Pattern) exists, match the pattern;
- When the pattern does not exist, create a new pattern, the function is a combination of match clause and create. After the merge clause, on creae and on match clauses can be explicitly specified to modify properties of bound nodes or relationships.
With the merge clause, you specify that a node must exist in the graph, that node must have certain labels, attributes, etc.
- The merge clause will create the corresponding node if it does not exist.
- Match the search pattern through the merge clause. The matching pattern is: a node has a Person tag and has a name attribute; if the pattern does not exist in the database, then create a new node; if the pattern exists, then bind the node;
1) Basics.
MERGE (m:Person {
name: ‘迈克尔·杰克逊’ })
RETURN m;
2) Specify the on create clause in the merge clause
If you need to create a node, then execute the on create clause to modify the attributes of the node;
MERGE (m:Person {
name: ‘杰森·斯坦森’ })
ON CREATE SET m.registertime = timestamp()
RETURN m.name, m.registertime
3) Specify the on match clause in the merge clause.
If the node already exists in the database, then execute the on match clause to modify the attributes of the node; if the node attribute does not exist, add it.
MERGE (m:Person)
ON MATCH SET m.registertime = timestamp()
RETURN m.name, m.registertime
4) Specify the on create and on match clauses in the merge clause at the same time , (if there is no corresponding attribute, the modification will fail, and no attribute will be added)
MERGE (m:Person{
name: ‘李连杰’ })
ON CREATE SET m.registertime = timestamp()
ON MATCH SET m.offtime = timestamp()
RETURN m.name, m.registertime,m.offtime
6) The merge clause is used to match or create a relationship
MATCH (m:Person {
name: ‘刘德华’ }),(n:Movie {
title: ‘神雕侠侣’ })
MERGE (m)-[r:导演]->(n)
RETURN m.name, type(r), n.title
7) The merge clause is used to match or create multiple relationships.
Zhao Wei is not only the director of Condor Heroes, but also the actor of Condor Heroes
MATCH (m:Person {
name: ‘赵薇’ }),(n:Movie {
title: ‘神雕侠侣’ })
MERGE (m)-[r:导演]->(n)<-[r2:出演]-(m)
RETURN m.name, type(r),type(r2), n.title
8) The merge clause is used for subqueries.
First add basic data and create city nodes:
create (n:City {
name: ‘北京’,othername:‘帝都’})
create (n:City {
name: ‘香港’,othername:‘HongKong’})
create (n:City {
name: ‘台湾’,othername:‘湾湾’})
9) Add an attribute bornin to each node of the Person tag,
match (n:Person)
set n.bornin = ‘’
return n;
match (n)
where id(n)=175
set n.bornin = ‘香港’
return n;
match (n)
where n.name=‘金城武’
set n.bornin = ‘台湾’
return n;
10) Requirements: Find the information of Andy Lau and Takeshi Kaneshiro and the othername of their location (equivalent to mysql linked table query)
MATCH (p:Person)
where p.name=‘刘德华’ or p.name=‘金城武’
MERGE (c:City {
name: p.bornin })
RETURN p.name,p.born,p.bornin , c.othername;
11) Create the relationship that Andy Lau's birthplace is Hong Kong
MATCH (a:Person),(c:City)
WHERE a.name = ‘刘德华’ AND c.name = ‘香港’
CREATE (a)-[r:出生地]->(c)
RETURN r;
12) Requirements: Create a birthplace relationship for each node in Person, and return null if there is no
MATCH (p:Person)
MERGE (c:City {
name: p.bornin })
MERGE §-[r:出生地]->(c )
RETURN p.name, p.bornin, c.othername;
13) Delete these relations
Match (a:Person)-[r:出生地]->(c:City{
name:’’}) delete r
Match (a:City)-[r:出生地]->(c:Person) delete r
14) Query the nodes whose name attribute does not exist in the Person tag
Match (n:Person) where not exists(n.name) return n
Match (n:Person) where not exists(n.name) delete n
create (n:Prize {
name: ‘金马奖’});
create (n:Prize {
name: ‘奥斯卡金奖’});
create (n:Prize {
name: ‘金鸡奖’});
create (n:Prize {
name: ‘香港电影金像奖’});
6.6 Functions related to entities
1) Use the id function to return the ID of the node or relationship
to query the id (node and relationship) that has a relationship with Andy Lau in the Person tag
MATCH (:Person {
name: ‘刘德华’ })-[r]->(movie)
RETURN id(r);
2) Use the type function to query the type of relationship.
Query the relationship related to Andy Lau in the Person tag (the following three results are the same)
MATCH (:Person {
name: ‘刘德华’ })-[r]->(a)
MATCH (:Person {
name: ‘刘德华’ })-[r]->(b)
MATCH (:Person {
name: ‘刘德华’ })-[r]->()
RETURN type(r);
3) Use the labels function to query the labels of the nodes
and query the nodes related to Andy Lau
MATCH (:Person {
name: ‘刘德华’ })-[r]->p
RETURN p;
4) Use the keys function to view the attribute keys of nodes or relationships
MATCH (a)
WHERE a.name = ‘刘德华’
RETURN keys(a)
5) View the properties of nodes or relationships through the properties() function
MATCH (a)
WHERE a.name = ‘刘德华’
RETURN properties(a)
reference
【1】https://blog.csdn.net/qq_42582489/article/details/125545454
【2】https://blog.csdn.net/qq_35793394/article/details/107833467
【3】https://blog.csdn.net/poxiaomeng187/article/details/82496157