You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLModel中指定Hash等类型的索引?

在SQLModel中使用Hash索引的方案
  • SQLModel自身的Field(index=True)参数仅支持创建默认的B-Tree索引,没有直接配置Hash索引的原生选项。由于它基于SQLAlchemy构建,确实需要借助SQLAlchemy的底层API来定义特定类型的索引。

  • 若要避免过度依赖特定数据库厂商,可通过SQLAlchemy的Index类结合数据库适配参数来实现Hash索引:
    以下是修改后的示例代码,同时兼容MySQL和PostgreSQL的Hash索引定义,对不支持Hash索引的数据库(如SQLite)会自动 fallback 到B-Tree索引:

    from sqlmodel import Field, Session, SQLModel, create_engine, select
    from sqlalchemy import Index
    
    
    class Hero(SQLModel, table=True):
        id: int | None = Field(default=None, primary_key=True)
        name: str
        secret_name: str
        age: int | None = Field(default=None)
        
        # 通过SQLAlchemy指定Hash索引,适配多数据库
        __table_args__ = (
            Index("ix_hero_name", "name", postgresql_using='hash', mysql_using='hash'),
            Index("ix_hero_age", "age", postgresql_using='hash', mysql_using='hash'),
        )
    
  • 需要注意的是:Hash索引并非SQL标准特性,不同数据库的实现差异极大,不存在完全跨所有数据库的通用Hash索引方案。如果你的应用需要强跨数据库兼容性,优先使用默认的B-Tree索引会更稳妥——它在等值查询场景下的性能足够应对大多数业务需求,同时支持范围、排序等更丰富的查询类型。

内容的提问来源于stack exchange,提问作者jbuddy_13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 01:15:08