【问题标题】:Create Clustered Columnstore index(MS SQL Server) using SqlAlchemy?使用 SqlAlchemy 创建聚集列存储索引(MS SQL Server)?
【发布时间】:2019-01-30 07:37:18
【问题描述】:

如何使用 SqlAlchemy python 库在表上创建聚集列存储索引?

我可以在文档here 中看到对聚集索引的支持,但找不到如何向其中添加 columnstore 关键字。

【问题讨论】:

  • 目前不支持列存储,这对我来说也很痛苦,在重建索引时使用列存储连接到数据库时,API 堆栈会导致应用程序崩溃

标签: python sql-server database orm sqlalchemy


【解决方案1】:

你可以通过监听表after_create事件并注入一些自定义SQL来解决这个问题:

engine = sqlalchemy.create_engine(...)
metadata = MetaData(engine)
table = students = Table(
   'students', metadata, 
   Column('id', Integer), 
   Column('name', String(100)), #Must be fixed length!
   Column('lastname', String(100)),
)

event.listen(
    table, 
    "after_create", 
    DDL("CREATE CLUSTERED COLUMNSTORE INDEX ix_%(table)s_columnstore ON %(fullname)s")
)

table.create()

Here's the documentation

More info on DDL()

【讨论】:

    【解决方案2】:

    sqlalchemy 允许您注入自定义 SQL 处理程序,所以这应该可以工作:

    # Create a custom mssql_columnstore argument for Indexes:
    Index.argument_for("mssql", "columnstore", None)
    
    # Custom SQL generator for columnstore indexes
    @compiles(CreateIndex, "mssql")
    def compile_create_index(create, compiler, **kw):
        preparer = compiler.preparer
        mssql_opts = create.element.dialect_options["mssql"]
    
        columnstore = mssql_opts.get("columnstore", None)
        if(not columnstore):
            stmt = compiler.visit_create_index(create, **kw)
            return stmt
    
        name = preparer.format_index(create.element)
        table_name = preparer.format_table(create.element.table)
        stmt = f"CREATE CLUSTERED COLUMNSTORE INDEX {name} ON {table_name}"
        return stmt
    
    engine = makeEngine()
    metadata = MetaData(engine)
    table = students = Table(
       'students', metadata, 
       Column('id', Integer), 
       Column('name', String(100)), 
       Column('lastname', String(100)),
       # Use the columnstore index flag here:
       Index('idx_id', mssql_columnstore = True),
    )
    
    
    table.create()
    

    I based this code on a previous stackoverflow answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2013-08-20
      相关资源
      最近更新 更多