Create different indexes for different searches - MongoDB

0

Hello,

At another time I needed to get posts similar to a specific one in the blog I'm developing, and this similarity is governed by the tags used in each post. Using MongoDB, I did this by creating an index on the tags, like this:

db.mypostscollection.createIndex({"tags": "text"});

And it works fine, I search for similar ones like this:

MyPostModel.find({
    $text: {
      $search: tags.replace(/\,/, ' ')
    }
  }, {
    score: {
      $meta: "textScore"
    }
  })
  .sort({
    score: {
      $meta: "textScore"
    }
  })

However, now you need to fetch the posts by their titles and content, and I thought of doing the following:

 db.mypostscollection.createIndex({"title":"text","subtitle":"text","mainContentText":"text"});

But since I already created the $ text index I can not do it again.

So how do I create searches independently? One for the tags, another for the match content.

Thank you in advance.

    
asked by anonymous 10.08.2017 / 16:26

1 answer

1

Why do you use text indexes? Their main idea is to search for text within a string attribute of the document. They are costly to create and maintain. Also, as you've noticed, you can only create a text index per collection.

You could use a normal index for these fields. Instead of specifying "text" in the type, you can put 1 for increasing indexes, and -1 for decreasing ones. In string fields the bank will use these indexes for regex searches, as long as they are for the beginning / end of the string (regex starting with ^ or ending with $).

I do not know your schema and application access patterns. But I think text type index would be interesting for the post body, you have more searchable words in that field. Not forgetting the high cost (performance and disk space) to keep this index!

For similar posts you can use $ in (whereas your tags is an array).

    
10.08.2017 / 19:18