用于解析服务器应用程序的MongoDB索引

问题描述:

我们有一个社交应用程序,用户可以在其中相互聊天,我们已经收到了35万条消息!

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

我们最近注意到,随着消息数量的增长,查找操作变得越来越慢!我相信这里的问题是 Message 集合未建立索引.

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.

这就是我现在要做的!我在MongoDB文档中找到了这段代码:

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))

这是我的留言集:

{
 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?

您的索引实际上应取决于查询的外观.假设您的消息查询如下:

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

然后,您将需要在Message集合上为此查询专门建立一个索引.在这种情况下:

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

要真正了解要构建的索引,您需要阅读Mongo文档

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

我个人将MLab用于我的Parse MongoDB,因为我对数据库不是很了解,而且它们实际上有一个缓慢的查询分析器,可以根据应用程序中的常见查询来推荐索引,因此如果您不想学习,MongoDB索引的优点,那么MLab是一个很好的起点

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