Indexes
Note that for setting a single field as unique, use the method on the field builder as follows:
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("phone").
Unique(),
}
}
Indexes can be configured on composition of fields and edges. The main use-case is setting uniqueness on fields under a specific relation. Let’s take an example:
ent/schema/city.go
ent/schema/street.go
// Street holds the schema definition for the Street entity.
type Street struct {
ent.Schema
}
// Fields of the Street.
func (Street) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
}
}
return []ent.Edge{
edge.From("city", City.Type).
Ref("streets").
Unique(),
}
}
// Indexes of the Street.
func (Street) Indexes() []ent.Index {
return []ent.Index{
index.Fields("name").
Edges("city").
Unique(),
}
}
example.go
Currently Edges
columns are always added after Fields
columns. However, some indexes require these columns to come first in order to achieve specific optimizations. You can work around this problem by making use of Edge Fields.
// Card holds the schema definition for the Card entity.
type Card struct {
ent.Schema
}
// Fields of the Card.
func (Card) Fields() []ent.Field {
Optional(),
field.Int("owner_id").
Optional(),
}
}
// Edges of the Card.
func (Card) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("card").
Field("owner_id").
Unique(),
}
}
// Indexes of the Card.
func (Card) Indexes() []ent.Index {
return []ent.Index{
index.Fields("owner_id", "number"),
}
}
Indexes currently support only SQL dialects, and do not support Gremlin. Dialect specific features are allowed using . For example, in order to use index prefixes in MySQL, use the following configuration:
The code above generates the following SQL statements:
CREATE INDEX `users_description` ON `users`(`description`(128))
CREATE INDEX `users_c1_c2_c3` ON `users`(`c1`(100), `c2`(200), `c3`)