Operating neo4j through python

Create nodes and relationships in neo4j

Create node

Create movie node

For example: Create a Movie node with three attributes {title: The Matrix’, released: 1999, tagline: Welcome to the Real World’}

CREATE (TheMatrix:Movie {<!-- -->title:'The Matrix', released:1999, tagline:'Welcome to the Real World'})

Create character nodes

For example: Create a Person node with two attributes: {name: Keanu Reeves’, born:1964}.

CREATE (Keanu:Person {<!-- -->name:'Keanu Reeves', born:1964})

Create relationship

Statements that create relationships between characters use the arrow operator. For example: (Keanu)-[:ACTED_IN {roles:[Neo’]}]->(TheMatrix) statement indicates the creation of a relationship where an actor participates in a movie. The actor Keanu participated in the ACTED_IN movie TheMatrix as the character Neo.

Create relationships between characters

CREATE
  (Keanu)-[:ACTED_IN {<!-- -->roles:['Neo']}]->(TheMatrix),
  (Carrie)-[:ACTED_IN {<!-- -->roles:['Trinity']}]->(TheMatrix),
  (Laurence)-[:ACTED_IN {<!-- -->roles:['Morpheus']}]->(TheMatrix),
  (Hugo)-[:ACTED_IN {<!-- -->roles:['Agent Smith']}]->(TheMatrix),
  (LillyW)-[:DIRECTED]->(TheMatrix),
  (LanaW)-[:DIRECTED]->(TheMatrix),
  (JoelS)-[:PRODUCED]->(TheMatrix)

Use python language to operate neo4j database

For python developers, the Py2neo library can complete operations on neo4j.
First install Py2neo and establish a database connection. Py2neo is installed using pip:

pip install py2neo

Connect to database

Example of code to establish a connection: define movie_db as the neo4j connection to be used [the default account password is “neo4j”, if it has been modified, it will be a new one, my password has been modified to “12345678”]

# Graph("http://127.0.0.1:7474",auth=("Account","Password"))
importpy2neo
Movie_db=Graph("http://localhost:7474",auth=("neo4j","12345678"))

An error may be reported when adding nodes later, == Cannot decode response content as JSON ==
At this time, you only need to modify the connection statement to: specify the connection database name=neo4j’

Movie_db=Graph("http://localhost:7474",auth=("neo4j","12345678"),name='neo4j')

Establish nodes and relationships

When creating a node, you need to define the node’s label and some basic attributes.

Node: node

Basic syntax:

node_1=Node(*labels, **properties)
Movie_db.create(node_1)

Note: In the code, the function of test_graph.create(node_1) is to put the locally created node into the database. Subsequent relationships, paths, etc., all require create after being created locally.

node_1 = Node('hero',name = 'Zhang Wuji')
node_2 = Node('Hero', name = 'Yang Xiao', force value='100')
node_3 = Node('sect',name = 'Mingjiao')

# Store in graph database
test_graph.create(node_1)
test_graph.create(node_2)
test_graph.create(node_3)
print(node_1)

Relationship: relationship

Basic syntax:

Relationship ((start_node, type, end_node, **properties))

For example, create two test nodes:

test_node_1 = Node(label = "person",name="test_node_1")# Header entity
test_node_2 = Node(label = "movie",name ="test_node_2")# Tail entity
#Movie_db.create(test_node_2)#Create the tail node

# relation
relation = Relationship(test_node_1, "DIRECTED", test_node_2)
#Create relationships (create nodes together)
Movie_db.create(relation)

Indicates the creation of two node relationships for test_node_1 and test_node_2. It should be noted that if the starting node does not exist when the relationship is established, this node will be established at the same time as the relationship is established.

Path:path

Basic syntax:

Path(*entities)

Note that entities are entities (relationships and nodes can be used as entities).
For example

from py2neo import Path
# Create a path: for example, query according to the path, or save the traversed results as a path
node_4,node_5,node_6 = Node(name='Ah Da'),Node(name='Ah Er'),Node(name='Ah San')
path_1 = Path(node_4,'little brother',node_5,Relationship(node_6, "little brother", node_5),node_6)
Movie_db.create(path_1)

print(path_1)

* Subgraph: Subgraph

A subgraph is an arbitrary collection of nodes and relationships, and is the base class for Node, Relationship, and Path.
Basic syntax:

Subgraph(nodes, relationships)

An empty subgraph is represented as None, and bool() can be used to test whether it is empty. Parameters must be entered as an array, as shown in the code below.

# Create a subgraph and update the database through the subgraph
node_1 = Node('hero',name = 'Zhang Wuji')
node_7 = Node('hero',name = 'Zhang Cuishan')
node_8 = Node('hero',name = 'Yin Susu')
node_9 = Node('Hero',name = 'Lion King')

relationship7 = Relationship(node_1,'biological father',node_7)
relationship8 = Relationship(node_1,'biological mother',node_8)
relationship9 = Relationship(node_1,'adopted father',node_9)
subgraph_1 = Subgraph(nodes = [node_7,node_8,node_9],relationships = [relationship7,relationship8,relationship9])
Movie_db.create(subgraph_1)

Delete node

Delete all nodes and relationships in the database:

Movie_db.delete_all()

Other deletion methods are as follows (the basis of deletion is query, as long as the query conditions are correct, the deletion will not be wrong):

# Delete all: use with caution
# Movie_db.delete_all()

#Delete by node id: Before deleting a node, you need to delete the relationship first. Otherwise, an error will be reported: ClientError
Movie_db.run('match (r) where id(r) = 3 delete r')
# Delete according to the name attribute: first add a separate node:
node_x = Node('hero',name ='Wei Yixiao')
Movie_db.create(node_x)
Movie_db.run('match (n:hero{name:\'Wei Yixiao\'}) delete n')

# Delete a node and the relationship connected to it
Movie_db.run('match (n:hero{name:\'Wei Yixiao\'}) detach delete n')
#Delete a certain type of relationship
Movie_db.run('match ()-[r:Like]->() delete r;')

# Delete subgraph
#delete(self, subgraph)

Modify node

The basis of modification is also query, and you can modify it if you find it. Therefore, the focus of this article is on query. The following example is simply modified.

# Change
# Change the Lion King's force value to 100
node_9['Force value']=100
# After local modification, you need to push it to the server.
Movie_db.push(node_9)

Query node

The nodes attribute of Movie_db contains information about all nodes in the graph. Please check the following code:

for node in Movie_db.nodes:
    print(node)

You can also use the match method to find the corresponding node, please refer to the following code:

n=Movie_db.nodes.match("Person")
for i in n:
    print(i)

Of course, more detailed matching can also be performed, please refer to the following code

n=Movie_db.nodes.match("Person",name='Keanu Reeves')
for i in n:
    print(i)

NodeMatcher

NodeMatcher: Locate nodes that meet specific conditions.
Basic syntax:

 NodeMatcher(graph).match(*labels, **properties)

Different effects can be achieved by combining different methods. The main method table is as follows:

td>

Method name Function
first() Returns the first Node in the query result, otherwise it returns empty
all() Returns all nodes
where(condition,properties) Second filtering of query results
order_by Order
# Define query
nodes = NodeMatcher(Movie_db)

#Single node, query according to label and name
## Query node: Lion King
node_single = nodes.match("hero", name="Lion King").first()
print('Single node query:\\
',node_single)

## Query all nodes according to label
node_hero = nodes.match("hero").all()
print('Data type of query result:',type(node_hero))

# Loop through the values in the query results and use first() to get the first value
i = 0
for node in node_hero:
    print('label query {} is: {}'.format(i,node))
    i + =1

## Query all nodes by name: use all() to get all values
node_name = nodes.match(name='Zhang Wuji').all()
print('name query result:',node_name)

#get() method queries nodes by id
node_id = nodes.get(1)
print('id query result:',node_id)

NodeMatch

NodeMatch: basic usage,

 NodeMatch(graph, labels=frozenset({<!-- -->}), predicates=(), order_by=(), skip=None, limit=None)

It can be seen that the parameters of NodeMatch and the parameters of NodeMatcher are completely different. Many conditions can be added later. The main methods included are as follows:

Method Function
iter(match) Traverse the matched nodes
len(match) Return the number of matched nodes
all() Returns all nodes
count() Returns node count, evaluates selected nodes
limit(amount), return the maximum number of nodes
order_by (*fields) Sort by the specified field or field expression. To reference the current node in a field or field expression, use the underscore character
where(*predicates, **properties) Secondary filtering
from py2neo import NodeMatch
nodess = NodeMatch(Movie_db,labels=frozenset({<!-- -->'hero'}))
# Traverse the queried nodes
print('='*15,'Traverse all nodes','='*15)
for node in iter(nodess):
    print(node)
# Query result count
print('='*15,'query result count','='*15)
print(nodess.count())
# Sort the query results according to the force value: pay attention to the way of quoting the field, precede it with an underscore and a dot: _.force value
print('='*10,'Sort the query results according to the force value','='*10)
wu = nodess.order_by('_.force value')
for i in wu:
    print(i)
    

RelationshipMatcher

RelationshipMatcher: A matcher used to select relationships that meet a specific set of criteria.
Basic syntax:

relation = RelationshipMatcher(Movie_db)
from py2neo import RelationshipMatcher
# Query a certain relationship
relation = RelationshipMatcher(Movie_db)

# None means any node! Does not mean empty
print('='*10,'hate relationship query results','='*10)
x = relation.match(nodes=None, r_type='hate')
for x_ in x:
    print(x_)
# Add two relationships
re1_1 = Relationship(node_101,'love rival',node_102)
re1_2 = Relationship(node_102,'love rival',node_103)
test_graph.create(re1_1)
test_graph.create(re1_2)
# Love rival query results
print('='*10,'hate relationship query results','='*10)
x = relation.match(nodes=None, r_type='love rival')
for x_ in x:
    print(x_)
    

RelationshipMatch

Basic syntax:

RelationshipMatch(graph, nodes=None, r_type=None, predicates=(), order_by=(), skip=None, limit=None)

It can be understood according to NodeMatch

refer to
https://zhuanlan.zhihu.com/p/437824721