我有以下Spring Data MongoDB文档:
@Document(collection = "messages")
@CompoundIndexes({ @CompoundIndex(name = "chatId_messageId", def = "{'chatId': 1, 'messageId': 1}") })
public class Message implements Serializable {
private static final long serialVersionUID = -1590112217771926691L;
@Id
private String id;
private Long chatId;
private Integer messageId;
private Post post;
}
Post
模型(不是Spring Data MongoDB文档)看起来像:
public class Post implements Serializable {
private static final long serialVersionUID = -886664249197573502L;
private String id;
}
我想将索引添加到Message.post.id
字段。
如何使用Message.post
文档中的Spring Data MongoDB和Message
字段声明来完成它?
答案 0 :(得分:1)
如果要将Message.post.id
添加到已经复合的索引中,请执行
@Document(collection = "messages")
@CompoundIndexes({ @CompoundIndex(name = "chatId_messageId", def = "{'chatId': 1, 'messageId': 1, 'Message.post.id' : 1}") })
public class Message implements Serializable {
private static final long serialVersionUID = -1590112217771926691L;
@Id
private String id;
private Long chatId;
private Integer messageId;
private Post post;
}
复合索引是具有多个索引字段的索引,因此理想情况下,限制性最强的字段应位于B树的左侧。例如,如果你想按性别和出生进行索引,那么指数应该从出生开始,因为它比性别更具限制性。
或者,如果您想将其视为一个单独的索引,那么使用@Indexed
创建索引,如
public class Post implements Serializable {
private static final long serialVersionUID = -886664249197573502L;
@Indexed
private String id;
}
有关如何查询复合索引的子字段的详细信息,请查看Documentation