MongoDB indexing for a Parse Server application

醉酒当歌 提交于 2021-02-08 03:38:11

问题


We have a social app where users can chat with each other and we’ve reached 350K messages!

We recently noticed that as the number of messages is growing, the find operations are getting slower! I believe the issue here is that the Message collection is not indexed.

That’s what I want to do now! I found this piece of code at the MongoDB docs:

db.comments.ensure_index(('discussion_id', 1))

This is my Message collection:

{
 chatRoom: <Pointer>,
 user: <Pointer>,
 text: <String>,
 isSeen: <Bool>
}

So I guess this is all I have to do:

db.Message.ensure_index(('chatRoom', 1))

Is that just it? Run this command and I’m all set? All existing and future messages will be indexed after that?


回答1:


Your index actually should depend on what your query looks like. Suppose your message query looks like this:

var query = new Parse.Query("Message");
query.equalTo("chatRoom", aChatRoom);
query.equalTo("user", someUser);
query.equalTo("isSeen", false);
query.descending("createdAt");
query.find().then(function(results){//whatever});

Then you would need to build an index on the Message collection specifically for this query. In this case:

db.Message.createIndex({_p_chatRoom:1, _p_user:1, isSeen: -1, _created_at: -1})

Alternatively, an index with just the chatroom will perform much better than no index at all

db.Message.createIndex({_p_chatRoom:1})

To really understand which indexes to build, you'll need to do some reading on the Mongo docs https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex

I personally use MLab for my Parse MongoDB, because I'm not very knowledgeable about databases, and they actually have a slow query analyzer that recommends indexes based on common queries in your application, so if you don't want to learn the finer points of MongoDB indexing, then MLab is a great place to start



来源:https://stackoverflow.com/questions/51767187/mongodb-indexing-for-a-parse-server-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!