GORM allows create database index with tag index
, uniqueIndex
, those indexes will be created when AutoMigrate or CreateTable with GORM
Index Tag
GORM accepts lots of index settings, like class
, type
, where
, comment
, expression
, sort
, collate
, option
Check the following example for how to use it
type User struct { |
uniqueIndex
tag uniqueIndex
works similar like index
, it equals to index:,unique
type User struct { |
Composite Indexes
Use same index name for two fields will creates composite indexes, for example:
// create composite index `idx_member` with columns `name`, `number` |
Fields Priority
The column order of a composite index has an impact on its performance so it must be chosen carefully
You can specify the order with the priority
option, the default priority value is 10
, if priority value is the same, the order will be based on model struct’s field index
type User struct { |
Shared composite indexes
If you are creating shared composite indexes with an embedding struct, you can’t specify the index name, as embedding the struct more than once results in the duplicated index name in db.
In this case, you can use index tag composite
, it means the id of the composite index. All fields which have the same composite id of the struct are put together to the same index, just like the original rule. But the improvement is it lets the most derived/embedding struct generates the name of index by NamingStrategy. For example:
type Foo struct { |
If the table Foo is created, the name of composite index will be idx_foo_myname
.
type Bar0 struct { |
Respectively, the name of composite index is idx_bar0_myname
and idx_bar1_myname
.
composite
only works if not specify the name of index.
Multiple indexes
A field accepts multiple index
, uniqueIndex
tags that will create multiple indexes on a field
type UserIndex struct { |