0

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 ?

1 Answer 1

1

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;
}

Updated

For more info regarding how queries with sub fields of compound index works, check Documentation

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. Will this index effectively work if I'll only query the documents by Message.post.id without chatId and messageId ?
I apologize, but it's hard to see the difference between your first and second solutions. Could you please clarify it ?
@alexanoid yes it should work. And for effective performance, the most variant field shoud be on the left side of the compound index
Thanks! I still don't understand from your second solution how to add Message.post.id (as the separate index) with @Indexed annotation? Could you please clarify it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.