0

I want to write a query to make the search operations on partial words but not getting any kind of solution other than Atlas Search. I have one solution to use regex but by using regex query is taking more time even after I have created index on them.

I text search method, we can only provide the complete word which is not the scenario in our case.

For eg. - {$text:{$search:'Lionel Messi'}}, it will go for Lionel and messi in the fields but,

if {$text:{$search:'ione'}}, this is the query then it is not giving any result because the word is not a complete match.

I can not use only regex here as it is very time taking so do you have any suggestions or solutions?

Is there any way to make the searching on partial text?

Thanks in Advance.

I have tried searching about this but got no success, all I can get is the solution to go for Atlas search only.

2 Answers 2

0

For simple partial text search you may consider $indexOfCP , it is known to outperform $regex unless it is some case where complex $regex is necessary, example:

db.collection.aggregate([
{
 $match: {
  $expr: {
    $gt: [
      {
        $indexOfCP: [
          "$key",
          "jump"
        ]
      },
      -1
    ]
  }
 }
 }
])

or

 db.collection.find( 
      { 
       $where: "this.key.indexOf('jump') >= 0" 
      } 
 ).hint({key:1})

Playground1

Playground2

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

1 Comment

It is working but fetch time is huge which is similar to regex, I have used it together with regex
0

My recommendation with MongoDB would be to create an ngram search collection. Have triggers for every document on save, to upsert a record to a "search" collection. This search collection will have a "parent" objectid referring to the source id, a "collection" string referring to the source collection name, and "value" string which would be an ngram of all the search properties.

Using mongoose you'd setup a "save" pre-middleware for all collections (other than "search") that would save fields to a search collection and a "delete/deleteMany" preware to clean up the search collection. Then, in your application, when you search, you will need to search on this single collection and pull the proper document via aggregate or separate queries.

If you are using MongoDB.com you can setup triggers inside Atlas instead of mongoose inside your application.

Edit: If you use mongoose, you can even use the built-in indexes to determine which fields need to be ngramed.

Comments

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.