python与neo-4j交互(对py2neo包做的笔记)

  • 2020 年 1 月 21 日
  • 筆記

1.连接数据库(三种方式相等)

123

graph_1 = Graph()graph_2 = Graph(host="localhost")graph_3 = Graph("http://localhost:7474/db/data")

2.事务操作 a)直接返回结果

1

graph.data("MATCH (a:Person) RETURN a.name, a.born LIMIT 4")

b)以pandas格式返回结果

1

DataFrame(graph.data("MATCH (a:Person) RETURN a.name, a.born LIMIT 4"))

事务操作样例

12345678910

from py2neo import Graph, Node, Relationshipg = Graph()tx = g.begin()a = Node("Person", name="Alice")tx.create(a)b = Node("Person", name="Bob")ab = Relationship(a, "KNOWS", b)tx.create(ab)tx.commit()g.exists(ab)

3.匹配关系 查找alice的所有朋友

12

for rel in graph.match(start_node=alice,rel_type="FRIEND"): print(rel.end_node()['name'])

4.带参数查询

12345

from py2neo import Graphg = Graph()# evaluate()返回结果的第一个值g.run(""MATCH (a) WHERE a.email={x} RETURN a.name",x="[email protected]").evaluate()g.run(""MATCH (a) WHERE a.email={x} RETURN a.name",x="[email protected]").data()

5.NodeSelector使用,可以使用Cypher语言的where部分

1234567

from py2neo import Graph,NodeSelectorgraph = Graph()selector = NodeSelector(graph)slected = selector.select("Person",name="Keanu Reeves")list(selected)selected = selector.select("Person").where("_.name =~ 'J.*'","1960 <= _.born < 1970")list(selected)

6.删除操作

12

# 删除所有的graph.delete_all()