我的对象模型如下所示,并希望您输入索引的数量以便更快地查询响应(在h2,mysql上)。假设和问题在以下模型下面给出。
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false, insertable = false, updatable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@ForeignKey(name = "fk_user_org_id")
@Index(name = "idx_user_org_id")
@JoinColumn(name = "org_id", nullable = false, referencedColumnName = "id")
@NotNull
private Organization organization;
@ManyToOne(fetch = FetchType.LAZY)
@ForeignKey(name = "fk_user_year_id")
@Index(name = "idx_user_year_id")
@JoinColumn(name = "year", nullable = false, referencedColumnName = "id")
@NotNull
private Year year;
@ManyToOne(fetch = FetchType.LAZY)
@ForeignKey(name = "fk_user_created_by")
@Index(name = "idx_user_created_by")
@JoinColumn(name = "created_by", nullable = false, referencedColumnName = "id")
@NotNull
private User createdBy;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "desc")
private String desc;
@Column(name = "is_system", length = LEN_1)
@Type(type = "org.hibernate.type.YesNoType")
private boolean isSystem = false;
@Column(name = "user_type", nullable = false)
private UserType userType;
@Column(name = "status", nullable = false)
@NotNull
private Status status;
}
我们的计划是使用多列索引而不是单列索引(即基于(organization,year,isSystem,status,userType,createdBy)创建索引user_idx)。假设我有这个索引,我是否会针对下面列出的查询获得优化的响应。
从用户中选择*,其中organization = 1和year = 2010并且createdBy ='Sam'或'Joe' [6]是否需要不同的多列索引,包括上述3列?
由于我们按照原始假设创建了一个多列索引,我是否可以安全地删除模型中当前定义的各个索引(idx_user_org_id,idx_user_year_id,idx_user_created_by)?
答案 0 :(得分:2)
您应该切换索引中列的顺序:
(organization, year, isSystem, userType, status, createdBy)
这样可以更好地为这两个查询提供服务:
select * from user where organization=1 and year=2010 and isSystem=false and userType=Manager
select * from user where organization=1 and year=2010 and isSystem=false and userType=Employee
[6]是否需要一个不同的多列索引,由上述3列组成?
它不需要一个新索引 - 它可以使用现有索引,但效率较低 - 只会使用前两列。为此查询添加新索引看起来不错。
我可以安全地删除单个索引
是。您应该删除未使用的索引,否则它们将占用磁盘空间并减慢表修改速度而不会带来任何好处。