Cypher query operation based on neo4j

Cypher query operation based on neo4j

1. Introduction to Cypher

Cypher is a graph query language proposed by Neo4j. It is a declarative graph database query language. It has streamlined syntax and powerful expressiveness, and can query and update graph data accurately and efficiently. It is a SQL-inspired language for describing visual patterns in graphs using ASCII-Art syntax. It allows stating what you want to select, insert, update, or delete from a graph database without describing exactly how to do it. With Cypher, users can build expressive and efficient queries that handle the required create, read, update, and delete functionality.

2. Cypher operation

Point type

n. device: internal ID, external unique identification id, name

m. Regulations: internal ID, external unique identification id, name

Relationship type

a. Terms of use: device–>Terms

b. Regulations: device–>device

2.1 Query MATCH

MATCH is used to retrieve nodes and relationships in a graph database.

(1) Basic node search

a) Query node:

MATCH (n)
RETURN n

b) Find the entity with the specified label

match (n: stipulation) //Colon is English
return n

c) Find the entity whose label is specified and whose ID is e29

match (n: stipulation {id:'e29'}) //Note that tags are not quoted and attributes must be quoted.
return n

(2) Query relationship

a) Query all relationships

MATCH r=()-->()
RETURN r
match ()-[r]->() //This way of writing finds the table format, not the picture
return r

b) Query all relationships of the label device

MATCH r=(n: stipulation)-->() //"out" relationship
RETURN r
MATCH r=()-->(n: stipulation) //"enter" relationship
RETURN r
MATCH r=(n: stipulation)--() //All relations about stipulations
RETURN r

c) Query all relationships of entities with label device and id e18

match r=(n:device{id:"e18"})--()
return r

d) Query the relationship between the label device and the label specified

match r=(n:device)--(m:regulation)
return r

e) Query the relationship between the entity (labeled deviceid is e18) and the entity (labeled deviceid is e18)

match r=(n:device{id:"e18"})--(m:device{id:"e1"})
return r

2.2 Create

2.2.1 create

Create directly, easy to cause duplication

(1) Create node

a) Create a “spec” tag

create (n: stipulation)
return n

b) Create an entity under the specified label

create (n:Regulations{id:"e29",name:"It is strictly prohibited to load iron and other foreign objects and explosive-resistant gunpowder, detonators, etc."}) //will be repeated
return n

(2)Create relationship

c) Create a relationship between two entities

OPTIONAL MATCH (n:device), (m: stipulation) //Left join to avoid Cartesian product
WHERE n.name = 'fluid coupling' AND m.id = 'e2112' //Similar to sql
CREATE (n)-[r: usage regulations]->(m)
RETURN r

c) Create multiple entities and create relationships between multiple entities at the same time

CREATE p=(n:device {id: 'e2114',name:"Loading belt conveyor"})-[r:Usage regulations]->(m:Regulations{ id: \ 'e2115' ,name:"Soft start device should be added"})<-[s:Usage regulations]-(h: device {id:"e2116",name: 'Upper belt conveyor machine'})
return *

2.2.2MERGE

MERGE query, if it cannot be found, create it to avoid duplication.

a) The search label is device and the name is “fluid coupling”. If it is not found, create it.

MERGE (n:device {name:'fluid coupling'})
RETURN n.name as val //as val is an alias for n.name

b) Find the character “Ahn Sung-ki” and the movie “Infernal Affairs”, and then find the relationship between them “appearing in the movie”. If the relationship cannot be found, create the relationship and return them

Examples are as follows:

MATCH (n:Character {Name:'Ahn Sung-ki'}), (m:Movie {Movie name:"Infernal Affairs"})
MERGE (n)-[r:starring in movies]->(m)
RETURN n. name, r, m. movie title

3) Search for the movie “Infernal Affairs”, if not found, create the movie “Infernal Affairs”, set its rating attribute to 7, and then return the movie

Examples are as follows:

MERGE (n:movie {movie name:"Infernal Affairs"})
ON CREATE SET n.rating = 7
RETURN n as val

4) Search for the movie “Infernal Affairs”, if the movie is found, set its rating attribute to 7, if not found, create the movie “Infernal Affairs”, and then return the movie

Examples are as follows:

MERGE (n:movie {movie name:"Infernal Affairs"})
ON MATCH SET n. rating = 8
RETURN n as val

5) Search for the movie “Infernal Affairs”. If the movie is found, set its rating attribute to 7. If it is not found, create the movie “Infernal Affairs”, set its rating attribute to 8, and then return the movie< /strong>

Examples are as follows:

MERGE (n:movie {movie name:"Infernal Affairs"})
ON CREATE SET n.rating = 7
ON MATCH SET n. rating = 8
RETURN n as val

2.3 Delete DELETE

DELETE is used to delete nodes and relationships

(1) Delete node

a) Delete all nodes

match(n) //The relationship must be deleted before deletion
delete(n)

a) Delete the label as the person and the ID is e2116

MATCH (n:character { id: 'e2116' })
DELETE n

b) Delete the entity tagged with the character ID e2116 and all relationships related to it

MATCH (n: Person { Name: 'e2116' }) //id can determine the content to be deleted, or (n{ Name: 'e2116' })
DETACH DELETE n //Use DETACH DELETE to delete the node and all one-hop relationships connected to it

(2) Delete relationship

a) Delete all relationships

MATCH ()-[r]-()
DELETE r;

b) Delete all relationships named “entity”

MATCH (n { device: 'entity' })-[r]->()
DELETE r

c) Delete the “attribute” relationship named “entity”

MATCH (n { device: 'entity' })-[r:property]->()
DELETE r //Only delete relationships and retain related nodes

2.4 Change

2.41 SET

a) Change attributes

Find the name “Downloading Belt Conveyor”, change its id attribute to e2117, and return his id and label

MATCH (n { name: 'Lower belt conveyor' })
SET n.id = 'e2117'
RETURN n.id

You can also use where to filter

MATCH (n:device )
WHERE ID(n)=8 // ID(n) is the id that comes with neo4j
SET n.id = 'e2118'
RETURN n.id

b) Set to NULL, which is equivalent to deleting the attribute

Find the entity with the label device and name “Downloading Belt Conveyor” and delete its name attribute

MATCH (n:device{ id: 'e2117' })
SET n.id = NULL
RETURN n.id

c) Change the system’s own label with ID 21 to “requirements”, and remove the original label “my_entity”

MATCH (n)
WHERE ID(n) = 21
SET n: regulations
REMOVE n:my_entity
RETURN n

e) Query multiple tag entities and add new tags “stipulations”

MATCH (n)
WHERE "Single bucket excavator purchasing and installation regulations" IN labels(n) OR "Processing system should comply with the regulations" IN labels(n) OR "Operating regulations" IN labels(n) OR "Drawing bucket Regulations to be followed by shovels" IN labels(n) OR "Regulations to be observed at crushing stations" IN labels(n) OR "Regulations for open pits" IN labels(n)
SET n: stipulation //The source tag is still there, use remove to delete the source tag
RETURN n

2.4.2 REMOVE

Properties used to remove nodes and relationships.

a) Delete attributes

Find the name “Wen Zhengrong” and delete his name attribute. Examples are as follows:

MATCH (n:device { name: 'Downloading belt conveyor' })
REMOVE n.name
RETURN n

b) Delete the tag device with id “e29”

MATCH (n: device{id=e'29'})
REMOVE n:device

2.5 Import csv file

LOAD CSV is used to load CSV files into Cypher statements. The csv file format is as follows:

Id,Name,Year
1,Alibaba,1999
2,Tencent,1998
3,Yahoo,1979
4,Google,1998

The neo4j desktop version needs to place the csv file in the corresponding folder (click?, click openfolder, and click import)

Import entities

LOAD CSV FROM "file:///entity_107.csv" AS line
CREATE (a:entity{Id: line[0], name: line[1], year: line[2]});

Import relationships

LOAD CSV FROM 'file:///roles_107.csv' AS row
MATCH (startNode:entity {Id: row[0]})
MATCH (endNode:entity {Id: row[1]})
MERGE (startNode)-[r:RELATIONSHIP_TYPE]->(endNode);

In Cypher, labels are static and do not support dynamic generation. Therefore, you cannot dynamically create labels based on a column of data in the data table directly in the query.

Dynamic labels can be implemented using the py2neo script. Data preprocessing is performed before importing data, and corresponding labels are assigned to nodes based on the value in the fourth column.

from py2neo import Graph, Node #Connect to Neo4j database

graph = Graph("bolt://localhost:7687", auth=("your_username", "your_password")) #Read CSV file

with open("your_data.csv", "r") as file:
    lines = file.readlines() #Traverse the data and create nodes

for line in lines:
    parts = line.strip().split(",")
    if len(parts) >= 3:
        label = parts[2] # The third column of data is used as a label
        name = parts[0] # Assume that the first column of data is the node name
        node = Node(label, name=name)
        graph.create(node)

Learning reference link: https://zhuanlan.zhihu.com/p/398323729
Created a new knowledge graph communication group: 946759155

syntaxbug.com © 2021 All Rights Reserved.