一、连接数据库
from py2neo import Graph
"""
host:服务器ip地址,默认为'localhost'
http_port:http协议——服务器监听端口,默认7474
https_port:https协议——服务器监听端口,默认7473
user:登录用户名,默认'neo4j'
password:登录密码,无默认值,故若数据库其他参数都为默认值,则可直接通过密码登录
name:指定为数据库的名称,如果不指定为neo4j的话,会出现以下报错:
py2neo.errors.ProtocolError: Cannot decode response content as JSON
"""
g = Graph('http://localhost:7474', auth=("neo4j", "88888888"), name="neo4j")
print("创建成功")
二、创建结点和边
2.1 两个结点+一条边创建
from py2neo import Graph, Node, Relationship
g = Graph('http://localhost:7474', auth=("neo4j", "88888888"), name="neo4j")
print("连接成功")
a = Node('Person', name='Alice')
b = Node('Person', name='Bob')
ab = Relationship(a, 'KNOWS', b)
g.create(ab)
print("创建成功")
2.2 多节点/边创建
# 新版
from py2neo import Graph, Node, Relationship, Subgraph
g = Graph('http://localhost:7474', auth=('neo4j', '88888888'), name="neo4j")
print("连接成功")
# 开始进行图数据库的操作
tx = g.begin()
# 结点创建(人)
li_elder_woman = Node("Person", name="李奶奶", age=66)
li_elder_man = Node("Person", name="李爷爷", age=67)
li_woman = Node("Person", name="李妈")
li_child = Node("Person", name="小李")
# 结点创建(动物)
cat = Node("Animal", name='cat')
dog = Node("Animal", name='dog')
wife = Relationship(li_elder_man, "妻子", li_elder_woman)
husband = Relationship(li_elder_woman, "丈夫", li_elder_man)
father = Relationship(li_woman, "父亲", li_elder_man)
mother = Relationship(li_woman, "母亲", li_elder_woman)
mother2 = Relationship(li_child, "母亲", li_woman)
child = Relationship(li_woman, "孩子", li_child)
child2 = Relationship(li_elder_woman, "孩子", li_woman)
child3 = Relationship(li_elder_man, "孩子", li_woman)
grandson = Relationship(li_elder_woman, "孙子", li_child)
grandson2 = Relationship(li_elder_man, "丈夫", li_child)
relation_list = Subgraph(relationships=[wife, husband, father, mother, child, grandson])
# 创建
tx.create(relation_list)
print("创建成功")
# 执行
try:
tx.commit()
print("执行成功")
except:
print("执行失败")
效果图
三、匹配节点
3.1 匹配所有节点
import connect
g = connect.connect()
# 匹配所有的结点
nodes = g.nodes.match()
for node in nodes:
# node是一个类,表示一个结点
print(node)
# 展示他的属性
for item in node.items():
# 这里是键值对,[key, value]
print("key=" + item[0] + ", value=" + str(item[1]))
print("label=" + str(node.labels))
print("=" * 10 + "结点属性" + "=" * 10)
# 展示所有节点的属性
for attr in dir(node):
print(attr)
3.2 匹配指定的节点
可以用匹配器来匹配:matcher = NodeMatcher(g)
from py2neo import NodeMatcher
import connect
g = connect.connect()
# 用来查找节点的对象
matcher = NodeMatcher(g)
# first 返回第一个符合条件的节点
print("=" * 20 + "测试1" + "=" * 20)
'''
用法一
nodes = matcher.match(label, attr1=value1, attr2=value2)
用法二
nodes = matcher.match(label).where("_.attr1=value1, _.attr2=value2")
'''
node1 = matcher.match('Person', name='小李').first()
# node1 = matcher.match('Person').where("_.name='小李'").first()
print("返回第一个符合要求的节点")
print(node1)
print("=" * 20 + "测试2" + "=" * 20)
node2 = matcher.match('Person', age=67).first()
print("返回第一个符合要求的节点")
print(node2)
# all 返回所有符合条件的节点
nodes = matcher.match('Person')
for node in nodes:
print('姓名:%s \t 年龄:%s '% (node['name'], node['age']))
注意:matcher.match返回的是一个对象,并不是节点数组,其中
- first方法:返回第一个匹配的节点
- all方法:返回所有匹配的节点,返回类型是个数组
四、更新节点
4.1 更新单个节点
import connect
from py2neo import NodeMatcher, Subgraph
g = connect.connect()
tx = g.begin()
# 找到你要找的Nodes
matcher = NodeMatcher(g)
# 修改单个节点
init_node = matcher.match("Person", name="李爷爷").first()
# init_node = matcher.match("Person").where('_.name="徐福贵"')
init_node['name'] = "李爷"
sub = Subgraph(nodes=[init_node])
tx.push(sub)
tx.commit()
print("执行成功")
4.2 更新多个节点
# 修改多个节点
from py2neo import NodeMatcher, Subgraph
import connect
g = connect.connect()
tx = g.begin()
# 找到你要找的Nodes
matcher = NodeMatcher(g)
init_node = matcher.match("Person")
new_nodes = []
for node in init_node.all():
node['name'] = "里" + node['name'][1:]
new_nodes.append(node)
# 制作图
sub = Subgraph(nodes=new_nodes)
# 将子图push进tx当中
tx.push(sub)
# 执行命令
tx.commit()
print("执行成功")
五、删除边
描述:一般都是删除边,没有说删除节点的,因为删掉节点的话,相应的边就会凭空出来。所以一般都是删除边。
5.1 当节点没有了相连接的边的时候,就会自动删掉该节点
from py2neo import NodeMatcher, RelationshipMatcher
import connect
g = connect.connect()
matcher = NodeMatcher(g)
r_matcher = RelationshipMatcher(g)
nodes = matcher.match('Person').all()
length = len(nodes)
for i in range(length):
node = nodes[i]
# nodes=[None,b] 表示所有以b为终点的关系
# nodes=[a,None] 表示所有以a为起点的关系
# nodes=[None,None] 表示所有节点的关系
relation1 = r_matcher.match(nodes=[node, None]).all()
relation2 = r_matcher.match(nodes=[None, node]).all()
for edge in relation1:
g.delete(edge)
for edge in relation2:
g.delete(edge)
print("第%i个节点删除成功" % i)
# print(relation)
# g.delete(relation)
# print("删除成功")
5.2 只删除边不删除节点
from py2neo import NodeMatcher, RelationshipMatcher
import connect
g = connect.connect()
matcher = NodeMatcher(g)
r_matcher = RelationshipMatcher(g)
li_1 = matcher.match('Person', name='里ob').first()
li_2 = matcher.match('Person', name='里lice').first()
relation = r_matcher.match(nodes=[li_2, li_1]).first()
print(relation)
g.separate(relation)
print("删除完成")
六、给两个节点新增关系
from py2neo import Relationship, NodeMatcher
import connect
g = connect.connect()
matcher = NodeMatcher(g)
li = matcher.match('Person', name='里李').first()
alice = matcher.match('Person', name='里lice').first()
relation = Relationship(li, '朋友', alice)
g.create(relation)
relation = Relationship(alice, '朋友', li)
g.create(relation)
print("添加关系完成")
七、命令形式执行代码
八、对象内容
8.1 cypher.Record
8.1.1 常用属性
- Record.data() :该方法返回一个包含所有数据的字典。
- Record.keys() :返回一个包含所有键的列表。
- Record.values() :返回一个包含所有值的列表。
- Record.items() :返回一个包含键-值对的列表。
8.1.2 常用方法
- Record.get(key, default=None) :获取指定键的值,如果键不存在,返回默认值。
- Record.contains(key) :检查键是否存在于记录中。
- Record.getitem(key) :获取指定键的值。
- Record.setitem(key, value) :设置指定键的值。
- Record.delitem(key) :删除指定键及其对应的值。
- Record.len() :返回记录中的键-值对数量。
8.2 matching.NodeMatch
8.1.1 常用属性
- graph: 表示与此NodeMatch对象关联的Neo4j图数据库。
- node_class: 表示匹配的节点的类。默认情况下,它是Node类,但您可以指定要匹配的特定节点类。
- labels: 一个节点标签的列表,表示要匹配的节点必须具有这些标签。
- order: 匹配结果的排序顺序,可以是升序或降序。
- limit: 限制匹配结果的数量,以便在结果中返回指定数量的节点。
8.1.2 常用方法
- where: 允许您添加额外的条件,以便过滤匹配的节点。可以使用NodeMatch对象的where方法来定义查询条件。
- return_: 指定要返回的节点属性或节点对象。
- order_by: 用于指定排序条件。
- limit: 用于限制匹配结果的数量。
- first: 返回匹配结果中的第一个节点。
- all: 返回所有匹配的节点。
- pluck: 返回匹配结果中的指定属性的值的列表。
- delete: 删除匹配的节点。
- detach_delete: 分离并删除匹配的节点。
8.3 data.node
8.3.1 常用属性
- identity: 节点唯一标识符
- labels: 表示节点的标签,通常是一个标签名称的字符串列表。
8.3.2 常用方法
- 标签相关方法
-
- has_label(label)
- add_label(label)
- remove_label(label)
- clear_labels()
- update_labels(label)
- 属性相关方法
-
- clear()
- get(name, default=None): 返回名为“name”的属性的值,如果名称丢失,则返回 “default”。
- items()
- keys()
- **update(properties, kwproperties)
- values()
8.4 RelationshipMatcher
8.4.1 常用属性
- graph: 表示与此 RelationshipMatcher 对象关联的 Neo4j 图数据库。
- relationship_type: 表示要匹配的关系类型的名称。可以指定特定的关系类型。
- direction: 指定关系匹配的方向,可以是INCOMING、OUTGOING 或 UNDIRECTED。
- start_node: 可以指定起始节点的条件,以过滤匹配的关系。
- end_node: 可以指定结束节点的条件,以过滤匹配的关系。
8.4.2 常用方法
- where: 允许您添加额外的条件,以便过滤匹配的关系。可以使用 RelationshipMatcher 对象的 where 方法来定义查询条件。
- return_ : 指定要返回的关系或关系属性。
- first: 返回匹配结果中的第一个关系。
- all: 返回所有匹配的关系。
- get: 根据关系的 ID 检索关系。
- create: 创建新的关系。
- delete: 删除匹配的关系。
- match_single: 返回一个单独的关系匹配查询。
8.5 Relationship
8.5.1 常用属性
- nodes: 返回一个二元组(开始节点,结束节点)
- start_node: 返回开始节点
- end_node: 返回结束节点
8.5.2 常用方法
- relationship属性相关方法(同node一样)
-
- clear()
- get(name, default=None): 返回名为“name”的属性的值,如果名称丢失,则返回 “default”。
- items()
- keys()
- **update(properties, kwproperties)
- values()