Create different indexes for different searches - Mongodb

Asked

Viewed 58 times

0

Hello,

At another time I needed to get posts similar to a specific blog I’m developing, and this similarity was governed by the tags used in each post. Using Mongodb, I achieved this by creating an index in the tags, thus:

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

And it works well, I do the search for similar like this:

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

However, now you need to search the posts by their titles and content, and I thought I’d do it this way:

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

But as I already created the index $text I can’t do it again.

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

Thanks in advance.

1 answer

1


Why are you using such indexes text? Their main idea is to search for text within a document string attribute. They are costly to create and maintain. Also, as you noticed, you can only create a text index by 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. In string fields the database will use these indices for regex queries, provided they are for the beginning/end of the string (regex starting with or ending with $).

I’m not familiar with your application schema and access patterns. But I think the content of the type text would be interesting for the body post, you have more search words in this field. Not forgetting the high cost (performance and disk space) to maintain this index!

For similar posts you can use the $in (whereas its tag field is an array).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.