我正在使用pyArango Python包创建几个集合(文档(顶点)和边)。如何使用现有的顶点和边以编程方式创建图形?我知道如何使用ArangoDB web界面“添加图形”来创建图形,但这需要一个繁琐的任务,因为有大量的集合。
发布于 2020-06-28 21:19:30
在检查来自WebGui的网络流之后,我发现Add graph实际上是在发送一个以Edge和Document连接名称作为字符串输入的json post请求。因此,阻止我们使用现有边和文档的是pyarango中默认的验证构建
def _checkCollectionList(lst):
for colName in lst:
if not COL.isCollection(colName):
raise ValueError("'%s' is not a defined Collection" % colName)
graphClass = GR.getGraphClass(name)
ed = []
for e in graphClass._edgeDefinitions:
if not COL.isEdgeCollection(e.edgesCollection):
raise ValueError("'%s' is not a defined Edge Collection" % e.edgesCollection)
_checkCollectionList(e.fromCollections)
_checkCollectionList(e.toCollections)
ed.append(e.toJson())
_checkCollectionList(graphClass._orphanedCollections)为了解决这个问题,我们只需要在创建图之前实现类。例如,我有两个文档集合people和department,我想创建一个图,其中:
假设我的arangodb中已经有集合"people“、"department”、"knowns“、"belongs_to”,创建图的代码如下:
from pyArango.collection import Collection, Field
from pyArango.graph import Graph, EdgeDefinition
class knowns(Edges):
pass
class belongs_to(Edges):
pass
class people(Collection):
pass
class department(Collection):
pass
# Here's how you define a graph
class MyGraph(Graph) :
_edgeDefinitions = [EdgeDefinition('knowns', ['people'], ['people']),
EdgeDefinition('belongs_to', ['people'], ['department'])]
_orphanedCollections = []
theGraph = arrango_db.createGraph(name="MyGraph", createCollections=False)请注意,类名与我传递到图形创建中的字符串完全相同。现在,我们已经在ArangoDB中创建了图形:

发布于 2021-04-12 20:05:09
另一种解决方案是使用type动态创建类,这在已经定义了节点和边的情况下很有用
from pyArango.graph import Graph, EdgeDefinition
from pyArango.collection import Collection, Edges
# generate the class for "knowns", inheriting class "Edges", etc.
_ = type("knowns", (Edges,), {})
_ = type("belongs_to", (Edges,), {})
_ = type("people", (Collection,), {})
_ = type("department", (Collection,), {})
# finally generate the class for the graph
_ = type(attribute+'Graph', (Graph,),
{"_edgeDefinitions" : [EdgeDefinition('knowns', ['people'], ['people']),
EdgeDefinition('belongs_to', ['people'], ['department'])],
"_orphanedCollections" : []})
db.createGraph(name=MyGraph, createCollections=False)https://stackoverflow.com/questions/62296655
复制相似问题