我想使用以下原始 SQL 在 PostgreSQL 中创建索引:
CREATE INDEX ix_action_date ON events_map ((action ->> 'action'), date, map_id);
我试图将此行放入模型类的 __table_args__
部分,但我做不到。然后我通过在 Alembic 迁移中使用原始 SQL 简单地解决了它。
conn = op.get_bind()
conn.execute(text("CREATE INDEX ..."))
并且只是在 __table_args__
中使用虚拟索引,例如:
Index('ix_action_date')
我唯一的问题是 Alembic 不接受同名的虚拟索引,每次我运行 revision --autogenerate
时,它都会告诉我以下内容:
SAWarning: Skipped unsupported reflection of expression-based index ix_action_date
% idx_name)
然后它将自动生成的索引添加到迁移文件中:
op.create_index('ix_action_date', 'events_map', [], unique=False)
我的问题是:
如何将原始 SQL 写入
__table_args__
索引?我怎样才能真正使我的虚拟索引概念发挥作用?我的意思是仅按名称进行比较的索引?
最佳答案
How can I write raw SQL into a
__table_args__
Index?
要指定公式索引,您必须为表达式提供一个文本元素
例子:
class EventsMap(Base):
__tablename__ = 'events_map'
__table_args__ = (Index('ix_action_date', text("(action->>'action'), date, map_id")),)
map_id = Column(Integer, primary_key=True)
date = Column(DateTime)
action = Column(JSONB)
How can I really make my dummy index concept work ? I mean an index which is only compared by name?
似乎没有必要让你的虚拟索引概念起作用。如上所示,要么在 __table_args__
中指定完整的索引表达式,要么在模型和委托(delegate)索引创建中完全省略它,作为由 sqlalchemy 处理的数据库迁移。
关于python - 用于添加索引的 SQLAlchemy/Alembic 原始 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51232401/