Spring Mongo(二)索引

系列 - Spring Mongo基本用法

yml

spring:
  data:
    mongodb:
      transactionEnabled: true
      # 允许实体类上的索引自动在 mongodb 表中建立相应的索引
      autoIndexCreation: true
      uri: @mongo.config.uri@

Java

@Document(collection = "users")
public class User {

    @Id
    private String id;
    
    @Indexed
    private String username;
    
    private String email;
    private int age;

    // getters and setters
}

Java

@Data
@Document("category")
@CompoundIndexes ({
@CompoundIndex(name = "cid_category_idx", def ="{'cid': 1, 'category': 1}", unique = true)
})
public class Category {
    @Id
    private String id;
}

唯一索引确保索引字段的值是唯一的,不能重复。

Java

@Document(collection = "employees")
public class Employee {

    @Id
    private String id;
    
    @Indexed(unique = true)
    private String email;
    
    private String name;
    private String position;

    // getters and setters
}

稀疏索引只索引那些包含索引字段的文档,而忽略那些没有该字段的文档

Java

@Document(collection = "logs")
public class Log {

    @Id
    private String id;
    
    @Indexed(sparse = true)
    private String userId;
    
    private String message;
    private Date timestamp;

    // getters and setters
}

TTL(Time-To-Live)索引用于从集合中自动删除超过指定时间的文档。

Java

@Document(collection = "sessions")
public class Session {

    @Id
    private String id;
    
    private String userId;
    
    @Indexed(expireAfterSeconds = 3600)
    private Date createdAt;
}

地理空间索引用于支持地理空间查询。

Java

@Document(collection = "places")
public class Place {

    @Id
    private String id;
    
    private String name;
    // GEO_2DSPHERE 球面数据
    // GEO_2D 线性数据
    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
    private double[] location; // [longitude, latitude]

    // getters and setters
}

文本索引用于支持全文搜索

Java

@Document(collection = "articles")
public class Article {

    @Id
    private String id;
    
    @TextIndexed
    private String title;
    
    @TextIndexed
    private String content;

    // getters and setters
}

文本索引用于支持全文搜索。

Java

@Document(collection = "articles")
public class Article {

    @Id
    private String id;
    
    @TextIndexed
    private String title;
    
    @TextIndexed
    private String content;

    // getters and setters
}

MongoDB支持任何单个字段的哈希索引。哈希函数折叠嵌入的文档并为整个值计算哈希,但不支持多键(即数组)索引。

Java

@Document("Test")
@Data
@Accessors(chain = true)
public class Test extends BasePo {
    @HashIndexed
    private String uuid;
    private String userId;
    private String username;
}

相关内容