Neo4j Note7:Python使用Neo4j

Neo4j Note7:Python使用Neo4j

安装

  • py2neo
pip install py2neo
 

使用

from py2neo import Graph graph = Graph("http://192.168.92.145:7474", auth=("neo4j", "123456")) print(graph)

数据

  • 数据准备,在浏览器端执行Cypher语句创建
# 创建人物节点 CREATE (n:Person {name:'john'}) RETURN n; CREATE (n:Person {name:'Sally'}) RETURN n; CREATE (n:Person {name:'Steve'}) RETURN n; CREATE (n:Person {name:'Mike'}) RETURN n; CREATE (n:Person {name:'Liz'}) RETURN n; CREATE (n:Person {name:'Shawn'}) RETURN n; # 创建地区节点 CREATE (n:Location {city:'Miami', state:'FL'}); CREATE (n:Location {city:'Boston', state:'MA'}); CREATE (n:Location {city:'Lynn', state:'MA'}); CREATE (n:Location {city:'Portland', state:'ME'}); CREATE (n:Location {city:'San Francisco', state:'CA'}); # 创建关系 MATCH (a:Person {name:'Shawn'}), (b:Person {name:'John'}) MERGE (a)-[:FRIENDS {since:2012}]->(b); MATCH (a:Person {name:'Mike'}), (b:Person {name:'Shawn'}) MERGE (a)-[:FRIENDS {since:2006}]->(b); MATCH (a:Person {name:'Sally'}), (b:Person {name:'Steve'}) MERGE (a)-[:FRIENDS {since:2006}]->(b); MATCH (a:Person {name:'Liz'}), (b:Person {name:'John'}) MERGE (a)-[:MARRIED {since:1998}]->(b); # 创建更多人的出生地 MATCH (a:Person {name:'Liz'}), (b:Location {city:'Boston'}) MERGE (a)-[:BORN_IN {year:1981}]->(b); MATCH (a:Person {name:'Mike'}), (b:Location {city:'San Francisco'}) MERGE (a)-[:BORN_IN {year:1960}]->(b); MATCH (a:Person {name:'Shawn'}), (b:Location {city:'Miami'}) MERGE (a)-[:BORN_IN {year:1960}]->(b); MATCH (a:Person {name:'Steve'}), (b:Location {city:'Lynn'}) MERGE (a)-[:BORN_IN {year:1970}]->(b);
notion image

查询

from py2neo import Graph,NodeMatcher,RelationshipMatcher graph = Graph("http://192.168.92.145:7474", auth=("neo4j", "123456")) # print(graph) # 查询节点类型,返回值类型是frozenset,是不能增删元素的集合。 print(graph.schema.node_labels) # 查询关系类型 print(graph.schema.relationship_types) # 使用NodeMatcher查询节点 node_matcher = NodeMatcher(graph) node = node_matcher.match("Person").where(name="john").first() print(node) # 使用RelationshipMatcher查询关系 relationship_matcher = RelationshipMatcher(graph) node1 = node_matcher.match("Person").where(name='Mike').first() relationship = list(relationship_matcher.match([node1], r_type=None)) print(relationship)
notion image

Cypher语句查询

cypher_ = "MATCH (n:Person) \ WHERE n.work='免费资源网' \ RETURN n.name AS name, n.age AS age " df = graph.run(cypher_).to_data_frame() # pd.DataFrame