环境配置
- 安装Neo4j及配置,略
- 安装Java及配置,略
- 安装py2neo:
conda install py2neo
- 启动环境:
neo4j console
- 关闭环境:
neo4j stop
或 Ctrl+C
常用语句
from py2neo import Graph
URI = "neo4j://localhost"
AUTH = (USER, PASSWORD)
graph = Graph(URI, auth=AUTH)
graph.delete_all()
Cypher语句
增
order = """
CREATE (f:Person {name: 'Father', age:30}),
(s:Person {name: 'Son', age:10}),
(:Person {name: 'Nobody', age:20}),
(f) - [:FAMILY_WITH {type: 'Father'}] -> (s)
"""
graph.run(order)
删
order = "MATCH (n:Person{name:'Nobody'}) DELETE n"
graph.run(order)
改
quey_update = """
MATCH (f:Person {name: 'Father'})-[r]->(s:Person {name: 'Son'})
DELETE r
CREATE (f)-[:FAMILY_WITH {type: 'Son'}]->(s)
"""
graph.update(quey_update)
查
query = "MATCH (n) RETURN n"
graph.run(query).to_data_frame()
面向对象
增
from py2neo import Subgraph
propertys = "Person"
father = Node(propertys, name="Father", age=30)
son = Node(propertys, name="Son", age=10)
nobody = Node(propertys, name="Nobody", age=20)
relation = Relationship(father, "FAMILY_WITH", son)
subgraph = Subgraph(nodes=[father, son, nobody], relationships=[relation])
graph.create(subgraph)
删
from py2neo import NodeMatcher
nodes = NodeMatcher(graph).match(name="Nobody")
if nodes.exists():
for node in nodes:
graph.delete(node)
改
from py2neo import RelationshipMatcher
relation = RelationshipMatcher(graph)
rel_match = relation.match(r_type="FAMILY_WITH")
if rel_match.exists():
for rel in rel_match:
rel['type'] = 'Son'
graph.push(rel)
relation.match().all()
查
from py2neo import NodeMatcher
node_matcher = NodeMatcher(graph)
nodes = node_matcher.match(propertys).all()
print(nodes)
from py2neo import NodeMatch
nodes = NodeMatch(graph, labels=frozenset({propertys})).all()
print(nodes)
from py2neo import RelationshipMatcher
rel_matcher = RelationshipMatcher(graph)
rels = rel_matcher.match(nodes=[father]).all()
for rel in rels: print(rel)
from py2neo import RelationshipMatch
rels = RelationshipMatch(graph, nodes=[father]).all()
for rel in rels: print(rel)