[knowledge map] py2neo basic operation (November 11, 2021)

Keywords: Python AI

1. Connect to Neo4j database

To operate Neo4j through python, you first need to install py2neo, which can be installed directly using pip.

pip install py2neo

After installation, open pycharm and call py2neo

from py2neo import Graph,Node,Relationship

test_graph = Graph (
	"http://localhost:7474", 
	username="neo4j", 
	password="neo4j"
)

After the neo4j server is installed, the default port number is 7474, so the local host is“ http://localhost:7474 " . The default user name and password are neo4j, but you can also enter them in the browser http://localhost:7474 , you will be prompted to change your password for the first time.

2. Establishment of nodes

py2neo.Node is used to establish a node. When establishing a node, its node type (label) and a basic property (including property_key and property_value) should be defined.

The following code establishes two test nodes for:

# Note: do not add "label =" here, otherwise the label will be displayed in the form of attribute rather than label
test_node_1 = Node("Person",name = "test_node_1") 
test_node_2 = Node("Person",name = "test_node_2")
neo_graph.create(test_node_1)
neo_graph.create(test_node_2)

The type (label) of these two nodes is Person, and both have the property_key as name, and the property_value as "test_node_1" and "test_node_2" respectively.

3. Establishment of relationship between nodes

The Relationship between nodes is directed, so when establishing a Relationship, you must define a start node and an end node. It is worth noting that the start node and the end node can be the same point, and the Relationship at this time is that this point points to itself.

node_1_call_node_2 = Relationship(test_node_1,'CALL',test_node_2)
node_1_call_node_2['count'] = 1
node_2_call_node_1 = Relationship(test_node_2,'CALL',test_node_1)
node_2_call_node_1['count'] = 2
neo_graph.create(node_1_call_node_2)
neo_graph.create(node_2_call_node_1)

As shown in the above code, test is established respectively_ node_ 1 points to test_node_2 and test_node_2 points to test_node_1 there are two relationships. The type of the relationship is "CALL". Both relationships have the attribute count and the value is 1.

Note: if the start node or end node does not exist when the relationship is established, this node is established at the same time as the relationship is established.

# Establish node
test_node_1 = Node("people",name = "Xiao Ming")
test_node_2 = Node("people",name = "Xiao Hong")
test_graph.create(test_node_1)
test_graph.create(test_node_2)

# Build relationships
node_1_call_node_2 = Relationship(test_node_1,'like',test_node_2)
# node_1_call_node_2['count'] = 1
node_2_call_node_1 = Relationship(test_node_2,'Detestable',test_node_1)
# node_2_call_node_1['count'] = 2
test_graph.create(node_1_call_node_2)
test_graph.create(node_2_call_node_1)

4. Delete node

test_node_3 = Node("people",name = "Xiao Gang")
test_graph.create(test_node_3)

test_graph.delete(test_node_3)

# Delete all
test_graph.delete_all()

5. Attribute assignment of node / relationship and update of attribute value

Use the push function to update the attribute value!

test_node_2['age'] = 20
test_graph.push(test_node_2)

test_node_2['age'] = 22
test_graph.push(test_node_2)

node_1_call_node_2['degree'] = 'very'
test_graph.push(node_1_call_node_2)

6. Find nodes and relationships through attribute values (find,find_one)

Through find and find_ The one function can find nodes and relationships according to types, attributes and attribute values.

Examples are as follows:

find_code_1 = neo_graph.find_one(
  label="Person",
  property_key="name",
  property_value="test_node_1"
)
print find_code_1['name']

Find and find_ The difference is:

find_ The return result of one is a specific node / relationship. You can directly view its attributes and values. If there is no node / relationship, return None.

The result returned by find is a cursor cursors, which must fetch all the found nodes / relationships through a loop.

Find associated nodes / relationships through nodes / relationships

If you have determined a node or relationship and want to find the relationship and node related to it, you can use match and match_one.

find_relationship = neo_graph.match_one(start_node=find_code_1,end_node=find_code_3,bidirectional=False)
print find_relationship

As shown in the above code, match and match_ The parameters of one include start_node,Relationship´╝îend_ At least one of the nodes.

Bidirectional: refers to whether the relationship can be bidirectional.

If False, the start node must be start_node, the end node must be end_node. If there is a Relationship parameter, the direction corresponding to the Relationship must be followed.

If True, you do not need to care about the direction, and the data in both directions will be returned.

match_relation  = neo_graph.match(start_node=find_code_1,bidirectional=True)
for i in match_relation:
    print i
    i['count']+=1
    neo_graph.push(i)

As shown in the above code, find and find_code_1 related relationships.

Only start is written for the parameters in match_ If the value of node and bidirectional is True, the direction problem will not be considered, and find is returned_ code_ 1 refers to all association relationships between the start node and the end node.

If the value of bidirectional is False, only find will be returned_ code_ 1 is all association relationships of the starting node.

Query with CQL, and the returned result is list

data1 = test_graph.run('MATCH (a:people) RETURN a')
print(data1, type(data1))
# "[< record a = (_214: person {Name: '\ u5c0f \ u660e'}) >, < record a = (_254: person {age: 22, name: '\ u5c0f \ u7ea2'}) >] < class' list '>"
print(data1[0]['a']['name'])
# "Xiao Ming"

You can use the run method to execute the Cypher statement and return the cursor cursors. Cursors must display the results through traversal

find_rela  = neo_graph.run("match (n:Person{name:'test_node_1'}) return n")
for i in find_rela  :
    print i

Check node

print(pd.DataFrame(test_graph.nodes.match('people')))
#     age name
# 0 Nan Xiaoming
# 1 22.0 little red
print(pd.DataFrame(test_graph.nodes.match('people', name='Xiao Hong')))
#     age name
# 0 22.0 little red

Check relationship

print(list(test_graph.match(r_type="like")))
# [(Xiaoming) - [: liking {degree: '\ u975e \ u5e38'}] - > (Xiaohong)]

print(list(test_graph.match(r_type="Detestable")))
# [(Xiaohong) - [: hate {}] - > (Xiaoming)]

7. Read

Can neo4j read files directly, such as csv?

The answer is yes. Cypher language can; The py2neo module can only be read by executing cypher language, without python functions or methods.

Examples of the official website are as follows:

LOAD CSV WITH HEADERS FROM 'https://neo4j.com/docs/cypher-manual/4.0/csv/artists-with-headers.csv' AS line
CREATE (:Artist { name: line.Name, year: toInteger(line.Year)})

reference resources: Link Link

Posted by massive on Thu, 11 Nov 2021 10:24:58 -0800