Лампочки: замена create() на get_or_create()
Я использую TitanGraphDB + Cassandra. Я запускаю Titan следующим образом
cd titan-cassandra-0.3.1
bin/titan.sh config/titan-server-rexster.xml config/titan-server-cassandra.properties
У меня есть оболочка Rexster, которую я могу использовать для связи с Titan+Cassandra выше.
cd rexster-console-2.3.0
bin/rexster-console.sh
Я хочу запрограммировать базу данных Titan Graph из моей программы на python. Для этого я использую пакет лампочек.
from bulbs.titan import Graph
Я хочу заменить мой вызов create() на get_or_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()
Сначала мне нужно создать ключ. Или он проверяет все атрибуты по умолчанию.
Я новичок в Python, и я действительно не понимаю значениеget_or_create('name',"James",{'name':'james')
почему атрибуты функции указываются так?
Определение функции для get_or_create() здесь
Любая помощь будет оценена.
1 ответ
Метод get_or_create() Bulbs ищет вершину в индексе и создает ее, если она не существует. Вы можете поставить get_or_create()
питон dict
свойств базы данных так же, как вы можете с create()
,
Увидеть...
- http://bulbflow.com/docs/api/bulbs/element/
- https://github.com/espeed/bulbs/blob/master/bulbs/element.py
Вот несколько примеров...
>>> # 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'}