1. 连接数据库
1
2
3 from pyorient.ogm import Config, Gragph
config = Config.from_url(server, user, pwd)
g = Graph(config)
2. 构造schema类
1
2
3
4
5
6
7
8
9
10
11 Node = declarative_node()
Relationship = declarative_relationship()
# 定义节点类,继承Node;定义关系时,继承Relationship
class OrientdbFile(Node):
element_type = 'file' # 表名
element_plural = 'files' #
file_id = Integer(nullable=False, unique=True)
emp_no = Integer(nullable=True, unique=False)
file_type = String(nullable=True, unique=False)
初始化schema
1
2g.create_all(Node.registry) # 创建节点
g.create_all(Relationship.registry) # 创建边绑定schema
若orientdb中已存在表,则只需要绑定相应的表即可。
from class
1
2g.include(Node.registry) # 绑定节点
g.include(Relationship.registry) # 绑定边from schema
1
2
3
4
5
6
7classes_from_schema = graph.build_mapping(
Node,
Relationship,
auto_plural = True)
# Initialize Schema in PyOrient
graph.include(classes_from_schema)
3. 插入数据
orientdb里,一条记录可以认为是表对象的一个实例。插入记录即新建一个对象实例。有两种方式实现。
使用broker
1
g.persons.create(id="1", name="张三")
1
2p = {"id": "2", "name": "李四"}
Person.objects.create(**p)原生方式
1
2p = {"id": "3", "name": "王五"}
g.create_vertex(Person, **p)
4. 查询数据
方式一
1
2
3result = g.persons.query().all()
for p in result:
print(p.id, p.name)1
2
31 张三
2 李四
3 王五方式二
1
2
3result = g.query(Person).all()
for p in result:
print(p.id, p.name)1
2
31 张三
2 李四
3 王五filter
1
result = g.persons.query(name='张三').all()
1
result = g.query(Person).filter(Person.name == "'张三'").all() # 备注:张三内层同样需要用引号包裹起来,源代码的问题,所以建议使用上面方式。
5. 修改数据
pyorient的ogm本身并没有实现update功能,可以简单通过删除后插入实现修改功能。
1 | ps = g.persons.query(name='张三').all() |
1 | 2 李四 |
6. 删除数据
1 | p_dict = {"name": "张三"} |
7. batch
批量操作
1 | batch = g.batch() |
1 | 李四 2 |
备注:
batch的key不能为纯数字,例如batch[‘12’],当然,batch[12]更不行。报错timeout,不解释。
batch的key必需明确,否则会不提交到库。
1
2
3
4
5
6
7
8batch = g.batch()
for i in range(10, 11):
batch.persons.create(name='name' + str(1), id=i)
batch.commit()
result = g.persons.query(id=10).all()
for r in result:
print(r.name, r.id)并没有任何输出,表明,记录并没有正确提交。