【问题标题】:How can I write a SQLAlchemy query that will return all descendants of a node in a graph?如何编写一个 SQLAlchemy 查询来返回图中节点的所有后代?
【发布时间】:2019-02-23 19:01:32
【问题描述】:

我正在开发一个应用程序,其中我的数据库对象通常有多个父对象和多个子对象,并且想创建一个 SQLAlchemy 查询来返回对象的所有后代。

意识到我基本上是在尝试将图形存储在 SQL 数据库中,我发现设置 self-referential many-to-many schema 可以帮助我完成大部分工作,但是我在编写查询以返回节点的所有后代时遇到问题.我尝试关注SQLA's recursive CTE example,这看起来是正确的方法,但在使其正常工作时遇到了问题。我认为我的情况与示例不同,因为在我的情况下,对 Node.child(和 Node.parent)的查询返回检测列表而不是 ORM 对象。

无论如何,下面的代码将建立一个简单的有向无环无环图,如下所示(其中方向被推断为从较高行到较低行):

a   b    c
 \ / \   |
  d   e  f
  |\ /
  g h     
  |
  i

而我正在寻找的是编写查询的帮助,该查询将为我提供节点的所有后代。

  • get_descendants(d) 应该返回 g、h、i

  • get_descendants(b) 应该返回 d、e、g、h、i

示例代码:

from sqlalchemy.orm import aliased

from sqlalchemy import Column, ForeignKey, Integer, Table, Text
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)

session = Session()

Base = declarative_base()

association_table = Table('association_table', Base.metadata,
                           Column('parent_id', Integer, ForeignKey('node.id'), primary_key=True),
                           Column('child_id', Integer, ForeignKey('node.id'), primary_key=True))


class Node(Base):
    __tablename__ = 'node'
    id = Column(Integer, primary_key=True)
    property_1 = Column(Text)
    property_2 = Column(Integer)

    # http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#self-referential-many-to-many-relationship
    child = relationship('Node',
                            secondary=association_table,
                            primaryjoin=id==association_table.c.parent_id,
                            secondaryjoin=id==association_table.c.child_id,
                            backref='parent'
                            )

Base.metadata.create_all(engine)

a = Node(property_1='a', property_2=1)
b = Node(property_1='b', property_2=2)
c = Node(property_1='c', property_2=3)
d = Node(property_1='d', property_2=4)
e = Node(property_1='e', property_2=5)
f = Node(property_1='f', property_2=6)
g = Node(property_1='g', property_2=7)
h = Node(property_1='h', property_2=8)
i = Node(property_1='i', property_2=9)



session.add_all([a, b, c, d, e, f, g, h, i])
a.child.append(d)
b.child.append(d)
d.child.append(g)
d.child.append(h)
g.child.append(i)
b.child.append(e)
e.child.append(h)
c.child.append(f)

session.commit()
session.close()

【问题讨论】:

    标签: python graph orm sqlalchemy many-to-many


    【解决方案1】:

    解决方案

    以下非常简单的自引用多对多递归 CTE 查询将返回查找 b 的所有后代所需的结果:

    nodealias = aliased(Node)
    
    descendants = session.query(Node)\
        .filter(Node.id == b.id) \
        .cte(name="descendants", recursive=True)
    
    descendants = descendants.union(
        session.query(nodealias)\
        .join(descendants, nodealias.parent)
    )
    

    测试

    for item in session.query(descendants):
        print(item.property_1, item.property_2)
    

    产量:

    b 2
    d 4
    e 5
    g 7
    h 8
    i 9
    

    哪个是b 及其所有后代的正确列表。

    完整的工作示例代码

    这个例子向Node 类添加了一个方便的函数,用于返回对象的所有后代,同时还计算从自身到其所有后代的路径:

    from sqlalchemy.orm import aliased
    from sqlalchemy import Column, ForeignKey, Integer, Table, Text
    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import relationship
    from sqlalchemy.orm import sessionmaker
    
    engine = create_engine('sqlite://', echo=True)
    Session = sessionmaker(bind=engine)
    
    session = Session()
    
    Base = declarative_base()
    
    association_table = Table('association_table', Base.metadata,
                               Column('parent_id', Integer, ForeignKey('node.id'), primary_key=True),
                               Column('child_id', Integer, ForeignKey('node.id'), primary_key=True))
    
    
    class Node(Base):
        __tablename__ = 'node'
        id = Column(Integer, primary_key=True)
        property_1 = Column(Text)
        property_2 = Column(Integer)
    
        # http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#self-referential-many-to-many-relationship
        child = relationship('Node',
                                secondary=association_table,
                                primaryjoin=id==association_table.c.parent_id,
                                secondaryjoin=id==association_table.c.child_id,
                                backref='parent'
                                )
    
        def descendant_nodes(self):
            nodealias = aliased(Node)
            descendants = session.query(Node.id, Node.property_1, (self.property_1 + '/' + Node.property_1).label('path')).filter(Node.parent.contains(self))\
                .cte(recursive=True)
            descendants = descendants.union(
                session.query(nodealias.id, nodealias.property_1, (descendants.c.path + '/' + nodealias.property_1).label('path')).join(descendants, nodealias.parent)
            )
            return session.query(descendants.c.property_1, descendants.c.path).all()
    
    
    Base.metadata.create_all(engine)
    
    a = Node(property_1='a', property_2=1)
    b = Node(property_1='b', property_2=2)
    c = Node(property_1='c', property_2=3)
    d = Node(property_1='d', property_2=4)
    e = Node(property_1='e', property_2=5)
    f = Node(property_1='f', property_2=6)
    g = Node(property_1='g', property_2=7)
    h = Node(property_1='h', property_2=8)
    i = Node(property_1='i', property_2=9)
    
    
    
    session.add_all([a, b, c, d, e, f, g, h, i])
    a.child.append(d)
    b.child.append(d)
    d.child.append(g)
    d.child.append(h)
    g.child.append(i)
    b.child.append(e)
    e.child.append(h)
    c.child.append(f)
    e.child.append(i)
    
    session.commit()
    
    
    for item in b.descendant_nodes():
        print(item)
    
    session.close()
    
    
    """
    Graph should be setup like this:
    
    a   b    c
     \ / \   |
      d   e  f
      |\ /|
      g h |    
      +---+
      i
    
    """
    

    输出:

    ('d', 'b/d')
    ('e', 'b/e')
    ('g', 'b/d/g')
    ('h', 'b/d/h')
    ('h', 'b/e/h')
    ('i', 'b/e/i')
    ('i', 'b/d/g/i')
    

    评论

    【讨论】:

    • 有没有办法为所有的父母做到这一点?也就是说,不只是一个对象,而是返回一个包含根及其所有后代的“列表列表”?似乎无法弄清楚如何一次对多个对象执行此操作。
    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多