如何使用现有集合(文档和边)创建图

时间:2020-06-10 05:45:45

标签: arangodb

我正在使用pyArango Python包来创建几个Collection(文档(顶点)和边)。如何使用现有的顶点和边以编程方式创建图形?我知道如何使用ArangoDB Web界面“添加图形”创建图形,但是由于大量的“收藏夹”,这需要繁琐的任务。

2 个答案:

答案 0 :(得分:0)

在检查了来自WebGui的网络流之后,我发现Add graph本质上是在发送带有EdgeDocument连接名作为字符串输入的json发布请求。因此,阻止我们使用现有边和文档的是在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)

要解决此问题,我们只需要在创建图之前首先实现类。例如,我有两个文档集合人员和部门,我想创建一个图形:

  • 人->已知->人
  • 人员->所属->部门

假设我的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中创建了图形: enter image description here

答案 1 :(得分:0)

当您已经定义了节点和边时,另一个有用的解决方案是使用 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)