索引

多个字段

索引可以在一个或多个字段上配置以提高数据检索速度,也可以定义其唯一性。

  1. package schema
  2. import (
  3. "entgo.io/ent"
  4. "entgo.io/ent/schema/index"
  5. )
  6. // User holds the schema definition for the User entity.
  7. type User struct {
  8. ent.Schema
  9. }
  10. func (User) Indexes() []ent.Index {
  11. return []ent.Index{
  12. // 非唯一约束索引
  13. index.Fields("field1", "field2"),
  14. // 唯一约束索引
  15. index.Fields("first_name", "last_name").
  16. Unique(),
  17. }
  18. }

请注意,如果要为单个字段设置唯一约束,请在字段生成器上使用 Unique 方法,如下:

  1. func (User) Fields() []ent.Field {
  2. return []ent.Field{
  3. field.String("phone").
  4. Unique(),
  5. }
  6. }

边上的索引

索引可以为字段和边的组合进行配置。 主要用法是在特定关系下设置字段的唯一性。 让我们来看一个例子:

er-city-streets

在上面的示例中,我们有一个带了许多 StreetCity,并且我们想设置每个城市的街道名称都是唯一的。

ent/schema/city.go

  1. // City holds the schema definition for the City entity.
  2. type City struct {
  3. ent.Schema
  4. }
  5. // Fields of the City.
  6. func (City) Fields() []ent.Field {
  7. return []ent.Field{
  8. field.String("name"),
  9. }
  10. }
  11. // Edges of the City.
  12. func (City) Edges() []ent.Edge {
  13. return []ent.Edge{
  14. edge.To("streets", Street.Type),
  15. }
  16. }

ent/schema/street.go

  1. // Street holds the schema definition for the Street entity.
  2. type Street struct {
  3. ent.Schema
  4. }
  5. // Fields of the Street.
  6. func (Street) Fields() []ent.Field {
  7. return []ent.Field{
  8. field.String("name"),
  9. }
  10. }
  11. // Edges of the Street.
  12. func (Street) Edges() []ent.Edge {
  13. return []ent.Edge{
  14. edge.From("city", City.Type).
  15. Ref("streets").
  16. Unique(),
  17. }
  18. }
  19. // Indexes of the Street.
  20. func (Street) Indexes() []ent.Index {
  21. return []ent.Index{
  22. index.Fields("name").
  23. Edges("city").
  24. Unique(),
  25. }
  26. }

example.go

  1. func Do(ctx context.Context, client *ent.Client) error {
  2. // 和 `Save`不同,当出现错误是 `SaveX` 抛出panic。
  3. tlv := client.City.
  4. Create().
  5. SetName("TLV").
  6. SaveX(ctx)
  7. nyc := client.City.
  8. Create().
  9. SetName("NYC").
  10. SaveX(ctx)
  11. // Add a street "ST" to "TLV".
  12. client.Street.
  13. Create().
  14. SetName("ST").
  15. SetCity(tlv).
  16. SaveX(ctx)
  17. // This operation fails because "ST"
  18. // was already created under "TLV".
  19. if err := client.Street.
  20. Create().
  21. SetName("ST").
  22. SetCity(tlv).
  23. Exec(ctx); err == nil {
  24. return fmt.Errorf("expecting creation to fail")
  25. }
  26. // Add a street "ST" to "NYC".
  27. client.Street.
  28. Create().
  29. SetName("ST").
  30. SetCity(nyc).
  31. SaveX(ctx)
  32. return nil
  33. }

完整示例请参阅 GitHub.

Index On Edge Fields

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.

  1. // Card holds the schema definition for the Card entity.
  2. type Card struct {
  3. ent.Schema
  4. }
  5. // Fields of the Card.
  6. func (Card) Fields() []ent.Field {
  7. return []ent.Field{
  8. field.String("number").
  9. Optional(),
  10. field.Int("owner_id").
  11. Optional(),
  12. }
  13. }
  14. // Edges of the Card.
  15. func (Card) Edges() []ent.Edge {
  16. return []ent.Edge{
  17. edge.From("owner", User.Type).
  18. Ref("card").
  19. Field("owner_id").
  20. Unique(),
  21. }
  22. }
  23. // Indexes of the Card.
  24. func (Card) Indexes() []ent.Index {
  25. return []ent.Index{
  26. index.Fields("owner_id", "number"),
  27. }
  28. }

Dialect Support

Dialect specific features are allowed using annotations. For example, in order to use index prefixes in MySQL, use the following configuration:

  1. // Indexes of the User.
  2. func (User) Indexes() []ent.Index {
  3. return []ent.Index{
  4. index.Fields("description").
  5. Annotations(entsql.Prefix(128)),
  6. index.Fields("c1", "c2", "c3").
  7. Annotations(
  8. entsql.PrefixColumn("c1", 100),
  9. entsql.PrefixColumn("c2", 200),
  10. )
  11. }
  12. }

The code above generates the following SQL statements:

  1. CREATE INDEX `users_description` ON `users`(`description`(128))
  2. CREATE INDEX `users_c1_c2_c3` ON `users`(`c1`(100), `c2`(200), `c3`)

Atlas Support

Starting with v0.10, Ent running migration with Atlas. This option provides more control on indexes such as, configuring their types or define indexes in a reverse order.

  1. func (User) Indexes() []ent.Index {
  2. return []ent.Index{
  3. index.Fields("c1").
  4. Annotations(entsql.Desc()),
  5. index.Fields("c1", "c2", "c3").
  6. Annotations(entsql.DescColumns("c1", "c2")),
  7. index.Fields("c4").
  8. Annotations(entsql.IndexType("HASH")),
  9. // Enable FULLTEXT search on MySQL,
  10. // and GIN on PostgreSQL.
  11. index.Fields("c5").
  12. Annotations(
  13. entsql.IndexTypes(map[string]string{
  14. dialect.MySQL: "FULLTEXT",
  15. dialect.Postgres: "GIN",
  16. }),
  17. ),
  18. // For PostgreSQL, we can include in the index
  19. // non-key columns.
  20. index.Fields("workplace").
  21. Annotations(
  22. entsql.IncludeColumns("address"),
  23. ),
  24. // Define a partial index on SQLite and PostgreSQL.
  25. index.Fields("nickname").
  26. Annotations(
  27. entsql.IndexWhere("active"),
  28. ),
  29. // Define a custom operator class.
  30. index.Fields("phone").
  31. Annotations(
  32. entsql.OpClass("bpchar_pattern_ops"),
  33. ),
  34. }
  35. }

The code above generates the following SQL statements:

  1. CREATE INDEX `users_c1` ON `users` (`c1` DESC)
  2. CREATE INDEX `users_c1_c2_c3` ON `users` (`c1` DESC, `c2` DESC, `c3`)
  3. CREATE INDEX `users_c4` ON `users` USING HASH (`c4`)
  4. -- MySQL only.
  5. CREATE FULLTEXT INDEX `users_c5` ON `users` (`c5`)
  6. -- PostgreSQL only.
  7. CREATE INDEX "users_c5" ON "users" USING GIN ("c5")
  8. -- Include index-only scan on PostgreSQL.
  9. CREATE INDEX "users_workplace" ON "users" ("workplace") INCLUDE ("address")
  10. -- Define partial index on SQLite and PostgreSQL.
  11. CREATE INDEX "users_nickname" ON "users" ("nickname") WHERE "active"
  12. -- PostgreSQL only.
  13. CREATE INDEX "users_phone" ON "users" ("phone" bpchar_pattern_ops)

Functional Indexes

The Ent schema supports defining indexes on fields and edges (foreign-keys), but there is no API for defining index parts as expressions, such as function calls. If you are using Atlas for managing schema migrations, you can define functional indexes as described in this guide.

Storage Key

Like Fields, custom index name can be configured using the StorageKey method. It’s mapped to an index name in SQL dialects.

  1. func (User) Indexes() []ent.Index {
  2. return []ent.Index{
  3. index.Fields("field1", "field2").
  4. StorageKey("custom_index"),
  5. }
  6. }