Spring Mongo(二)索引
系列 - Spring Mongo基本用法
目录
配置MongoDB索引生效
spring:
data:
mongodb:
transactionEnabled: true
# 允许实体类上的索引自动在 mongodb 表中建立相应的索引
autoIndexCreation: true
uri: @mongo.config.uri@
通过Mongo配置索引
单字段索引
@Document(collection = "users")
public class User {
@Id
private String id;
@Indexed
private String username;
private String email;
private int age;
// getters and setters
}
多键索引
@Data
@Document("category")
@CompoundIndexes ({
@CompoundIndex(name = "cid_category_idx", def ="{'cid': 1, 'category': 1}", unique = true)
})
public class Category {
@Id
private String id;
}
唯一索引(Unique Index)
唯一索引确保索引字段的值是唯一的,不能重复。
@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
}
稀疏索引(Sparse Index)
稀疏索引只索引那些包含索引字段的文档,而忽略那些没有该字段的文档
@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 索引(TTL Index)
TTL(Time-To-Live)索引用于从集合中自动删除超过指定时间的文档。
@Document(collection = "sessions")
public class Session {
@Id
private String id;
private String userId;
@Indexed(expireAfterSeconds = 3600)
private Date createdAt;
}
地理空间索引(Geospatial Index)
地理空间索引用于支持地理空间查询。
@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
}
文本索引(Text Index)
文本索引用于支持全文搜索
@Document(collection = "articles")
public class Article {
@Id
private String id;
@TextIndexed
private String title;
@TextIndexed
private String content;
// getters and setters
}
文本索引(Text Index)
文本索引用于支持全文搜索。
@Document(collection = "articles")
public class Article {
@Id
private String id;
@TextIndexed
private String title;
@TextIndexed
private String content;
// getters and setters
}
哈希索引(Hash Index)
MongoDB支持任何单个字段的哈希索引。哈希函数折叠嵌入的文档并为整个值计算哈希,但不支持多键(即数组)索引。
@Document("Test")
@Data
@Accessors(chain = true)
public class Test extends BasePo {
@HashIndexed
private String uuid;
private String userId;
private String username;
}