叽叽喳喳,嘻嘻哈哈

导航

pyorient

简介

 pyorient是orientdb的python库

 该库提供两种访问orientdb的方式:1、client 的方式

 2、ogm 的方式(类似于ORM)

由于OGM 封装了client,且由于OGM 易于理解,操作简单,所以,这里主要介绍OGM

创建/连接数据库

导入OGM 所需模块

from pyorient.ogm import Graph, Config

实例化 graph

config = Config.from_url('/localhost/test','root','root')
graph = Graph(config,'admin','admin')

 

  • config 中的两个 root 分别为orientdb 实例的用户名和密码。类似于如下命令

orientdb > connect remote:localhost root root

graph 中的两个 admin 即想要连接的数据库的用户名和密码

  • 由于Graph() 会调用open 方法,所以,如果数据库中没有将要连接的数据库,那么就会创建一个新的,相应的数据库。

操作数据库

映射

 ORM类似,OGM会将 python 代码中的 class 映射到orientdb中的class。相当于关系型数据库中的表;python中class的属性即为orientd中class的property。即相当于关系型数据库中表的字段/列

 想要将python中的class 映射到orientdb 中的class,需要将python中的class进行注册。

代码如下:

from pyorient.ogm.declarative import declarative_node, declarative_relationship

Node = declarative_node()
Relationship = declarative_relationship()

class Person(Node):
    pass

class Likes(Relationship):
    pass

graph.create_all(Node.registry)
graph.create_all(Relationship.registry)

  • 每一次调用declarative_node( )  declarative_relationship( ) 都会生成相应的注册表。其实Node和Relationship是两个基类。
  • create_all( ) 命令就会在orientdb中创建相应的class,如果该class已经存在,那么就会更新该class。

Boker (代理)

 OGM 拥有多层映射。

 上面提到的python class 到 orientdb class 是一层映射。另一层映射是python class 的object(对象) 和orientdb中具体的 vertex 和 edge 之间的映射。Boker 即工作在这一层。该层映射成功后,会自动为每一个class 创建个一个boker对象。需要注意的是vertex类需要有element_plural 属性,relationship类需要有 label 属性。

代码如下:

class Foo(Node):
    element_plural = 'foos'
    name = String()
class Friend(Relationship):
    label = 'friends'
graph.include(Node.registry)   
graph.foos.create(name='Bar')
Foo.objects.create(name='Baz')

find_bar = graph.foos.query(name='Bar')

  • graph.foos Foo.objects 都是一样的,都是boker对象。
  • Relationship 的子类,在orientdb中 是用 label 来命名类名的。如 Friend 类在数据库中的类名为friends
  • query() 反回的是一个查询集对象。

命令

inE()  outE() bothE()

 返回进/出/进出自一个顶点或者类的 边的对象

in_() out() both()

返回 /出/进出 自一个边的或者类的 顶点的对象。

get_vertex()  get_edge()  get_element()

获取 顶点/边/顶点或者边

element 包括顶点和边两种对象。

create_class()  create_vertex() create_edge() drop_class()

创建 顶点或边/顶点/边 ; 删除类

open()   drop()

打开/关闭一个数据库

  调用open( )时,如果该数据库不存在,则自动创建。

 调用drop( ) 时,需要有一个已经打开的数据库。

query()

返回一个query对象。具有all count group_by order_by filter 等方法,可以对查询结果进行处理。

update()   clear_registry()

更新python中orientdb对象的元素注册表 /清除元素注册表

 

字段类型

 OGM中,python类的属性就是orientdb 的property,也就是相当于关系型数据库中的字段/列。在pyorient中,字段类型有 String Boolean Float Date 等类型。这些字段又有如下属性。

name 会覆盖掉 “=” 前面命名的属性名。

nullable 允许为空

readonly 只读

default 默认值

indexed 是否为索引值

unique 是否唯一,如果为真,那么会创建相应的索引。

mandatory 是否强制有值。如果没有设置可以为空,那么默认设定为强制有值。

posted on 2017-04-06 11:21  叽叽喳喳,嘻嘻哈哈  阅读(410)  评论(0编辑  收藏  举报