1

我正在使用 TitanGraphDB + Cassandra。我按如下方式启动 Titan

cd titan-cassandra-0.3.1
bin/titan.sh config/titan-server-rexster.xml config/titan-server-cassandra.properties

我有一个 Rexster shell,可以用来与上面的 Titan+Cassandra 通信。

cd rexster-console-2.3.0
bin/rexster-console.sh

我想从我的 python 程序中对 Titan Graph DB 进行编程。我为此使用了灯泡包。

我使用如下所示的灯泡从 python 创建了 3 种类型的顶点。3种类型的顶点是

- switch
- port
- device

from bulbs.titan import Graph
 vswitch = self.g.vertices.get_or_create('dpid',dpid_str,{'state':'active','dpid':dpid_str,'type':'switch'})
 vport   = self.g.vertices.get_or_create('port_id',port_id,{'desc':desc,'port_id':port_id,'state':state,'port_state':port_state,'number':number,'type':'port'})

如果我尝试打印变量 vswitch、vport 和 vdevice,我会得到以下结果。

vswitch     <Vertex: http://localhost:8182/graphs/graph/vertices/4>
vport       <Vertex: http://localhost:8182/graphs/graph/vertices/28>

但是,如果我尝试使用如下键检索上述顶点。

vswitch = self.g.vertices.index.lookup(dpid=dpid_str)
vport   = self.g.vertices.index.lookup(port_id=port_id_str)

并尝试打印出 vswitch 和 vport 变量我得到以下值

<generator object <genexpr> at 0x26d6370>)
<generator object <genexpr> at 0x26d63c0>

我在尝试使用 g.vertices.index.lookup(dpid=dpid_str) 检索上述顶点时做错了什么

4

1 回答 1

1

Bulbsg.vertices.index.lookup()方法返回一个Python 生成器(它是一种迭代器)。

用于next()获取生成器中的下一个值:

>>> # lookup() returns an generator (can return more than 1 value)

>>> switches = self.g.vertices.index.lookup(dpid=dpid_str)
>>> switch = switches.next()

>>> ports   = self.g.vertices.index.lookup(port_id=port_id_str)
>>> port = ports.next()

或者您可以使用list()将其generator转换为 Python list

>>> switches = self.g.vertices.index.lookup(dpid=dpid_str)
>>> list(switches)

>>> ports   = self.g.vertices.index.lookup(port_id=port_id_str)
>>> list(ports)

但是,如果索引项是唯一的,则可以使用该get_unique()方法返回一个值或None

# returns 1 vertex or None (errors if more than 1)
>>> vertex = g.vertices.index.get_unique( "dpid", dpid_str) 

看...

Rexter 索引文档:

index.lookup() https://github.com/espeed/bulbs/blob/afa28ccbacd2fb92e0039800090b8aa8bf2c6813/bulbs/titan/index.py#L251

index.get_unique() https://github.com/espeed/bulbs/blob/afa28ccbacd2fb92e0039800090b8aa8bf2c6813/bulbs/titan/index.py#L274

注意:迭代器和生成器是 Python 编程的基础——它们无处不在,并不特定于灯泡——如果您是 Python 编程的新手,请参阅我对如何学习 Python 编程的回答?获取用于学习 Python 编程的良好在线资源列表。

于 2014-06-17T19:27:54.077 回答