Reputation: 25882
I have the following Spring Data MongoDB document:
@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;
}
the Post
model(which is not Spring Data MongoDB document) looks like:
public class Post implements Serializable {
private static final long serialVersionUID = -886664249197573502L;
private String id;
}
I'd like to add index to the Message.post.id
field.
How it can be done with Spring Data MongoDB and Message.post
field declaration in Message
document ?
Upvotes: 0
Views: 1144
Reputation: 6932
If you want to add Message.post.id
to an already compound index, then do it like
@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;
}
Compound indexes are indexes that have more than one indexed field, so ideally, the most restrictive field should be to the left of the B-tree. If you want to index by sex and birth, for instance, the index should begin by birth, as it is much more restrictive than sex.
Or if you want to treat it as a saperate index, then create index using @Indexed
like
public class Post implements Serializable {
private static final long serialVersionUID = -886664249197573502L;
@Indexed
private String id;
}
For more info regarding how queries with sub fields of compound index works, check Documentation
Upvotes: 1