【问题标题】:Bulbs: replacing create() with get_or_create()灯泡:用 get_or_create() 替换 create()
【发布时间】:2023-08-11 18:34:01
【问题描述】:

我正在使用 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 进行编程。我为此使用了灯泡包。

from bulbs.titan import Graph

我想用 get_or_create() 替换我的 create() 调用

我在网上看到了下面这个例子。

 james = g.vertices.create(name="James")

如下图所示。

 james = g.vertices.get_or_create('name',"James",{'name':'james')

现在我的顶点创建函数如下。

self.g.vertices.create({ 'desc':desc,
                         'port_id':port_id,
                         'state':state,
                         'port_state':port_state,
                         'number':number,
                         'type':'port'} )

如果我想重写上面的函数调用 (create()),它使用 get_or_create() 接受多个键值对

我首先需要创建一个key。或者它是否默认检查所有属性。

我是python初学者,不太明白
get_or_create('name',"James",{'name':'james')

的意义

为什么要这样指定函数属性?

get_or_create() 的函数定义是here

任何帮助将不胜感激。

【问题讨论】:

    标签: python cassandra titan bulbs


    【解决方案1】:

    Bulbs 'get_or_create()' 方法在索引中查找一个顶点,如果它不存在则创建它。您可以像使用 create() 一样提供 get_or_create() 和 Python dict 的数据库属性。

    看...

    这里有几个例子...

    >>> # a vertex where name is "James" doesn't exist so lookup() returns None
    >>> g.vertices.index.lookup("name", "James")  
    None
    
    >>> # a vertex where name is "James" doesn't exist so a vertex is created
    >>> data = dict(name="James", city="Dallas")
    >>> james = g.vertices.get_or_create("name", "James", data)
    >>> james.data()
    {'city': 'Dallas', 'name': 'James'}
    
    >>> james.eid   # returns the element ID for the james vertex    
    >>> 1       
    
    >>> # a vertex where name is "James" DOES exist so vertex is returned unmodified 
    >>> data = dict(name="James", city="Dallas", age=35)
    >>> james = g.vertices.get_or_create("name", "James", data)
    >>> james.data()         # note age=35 was not added to the vertex properties
    {'city': 'Dallas', 'name': 'James'}     
    
    >>> # one way to update the vertex properities
    >>> james.age = 35   
    >>> james.save()
    
    >>> james.data()
    >>> {'city': 'Dallas', 'age': 35, 'name': 'James'}
    
    >>> # a way to update the vertex properties if you only have the vertex ID
    >>> # the vertex ID for the james vertex is 1
    >>> data = dict(name="James", city="Dallas", age=35)
    >>> g.vertices.update(1, data)           
    
    >>> james = g.vertices.get(1)
    >>> james.data()
    >>> {'city': 'Dallas', 'age': 35, 'name': 'James'}
    

    【讨论】:

      最近更新 更多