0%

Orientdb 基本操作

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)
  1. 初始化schema

    1
    2
    g.create_all(Node.registry) # 创建节点
    g.create_all(Relationship.registry) # 创建边
  2. 绑定schema

    若orientdb中已存在表,则只需要绑定相应的表即可。

    • from class

      1
      2
      g.include(Node.registry) # 绑定节点
      g.include(Relationship.registry) # 绑定边
    • from schema

      1
      2
      3
      4
      5
      6
      7
      classes_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
    2
    p = {"id": "2", "name": "李四"}
    Person.objects.create(**p)
  • 原生方式

    1
    2
    p = {"id": "3", "name": "王五"}
    g.create_vertex(Person, **p)

4. 查询数据

  • 方式一

    1
    2
    3
    result = g.persons.query().all()
    for p in result:
    print(p.id, p.name)
    1
    2
    3
    1 张三
    2 李四
    3 王五
  • 方式二

    1
    2
    3
    result = g.query(Person).all()
    for p in result:
    print(p.id, p.name)
    1
    2
    3
    1 张三
    2 李四
    3 王五
  • filter

    1
    result = g.persons.query(name='张三').all()
    1
    result = g.query(Person).filter(Person.name == "'张三'").all()  # 备注:张三内层同样需要用引号包裹起来,源代码的问题,所以建议使用上面方式。

5. 修改数据

pyorient的ogm本身并没有实现update功能,可以简单通过删除后插入实现修改功能。

1
2
3
4
5
6
7
8
9
ps = g.persons.query(name='张三').all()
for p in ps:
g.delete_vertex(Person, {"name": "张三"})
p_dict = dict(name=p.name, id=p.id)
p_dict.update({"name": "张麻子"})
g.create_vertex(Person, **p_dict)
result = g.persons.query().all()
for p in result:
print(p.id, p.name)
1
2
3
2 李四
3 王五
1 张麻子

6. 删除数据

1
2
p_dict = {"name": "张三"}
g.delete_vertex(Person, **p_dict)

7. batch

批量操作

1
2
3
4
5
6
7
8
batch = g.batch()
for i in range(5, 10):
batch['f' + str(i)] = batch.persons.create(name='name' + str(1), id=i)
batch.commit()

result = g.persons.query().all()
for r in result:
print(r.name, r.id)
1
2
3
4
5
6
7
8
李四 2
name1 5
王五 3
name1 6
张麻子 1
name1 7
name1 8
name1 9

备注:

  1. batch的key不能为纯数字,例如batch[‘12’],当然,batch[12]更不行。报错timeout,不解释。

  2. batch的key必需明确,否则会不提交到库。

    1
    2
    3
    4
    5
    6
    7
    8
    batch = 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)

    并没有任何输出,表明,记录并没有正确提交。