Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an index for partial text search on MongoDB?

I'm following the tutorial instruction: https://docs.mongodb.com/manual/core/index-text/

This is the sample data:

db.stores.insert(
   [
     { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
     { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
     { _id: 3, name: "Coffee Shop", description: "Just coffee" },
     { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
     { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
   ]
)

Case 1: db.stores.find( { $text: { $search: "java coffee shop" } } ) => FOUND

Case 2: db.stores.find( { $text: { $search: "java" } } ) => FOUND

Case 3: db.stores.find( { $text: { $search: "coff" } } ) => NOT FOUND

I'm expecting case 3 is FOUND because the query is matches a part of java coffee shop

like image 630
Vũ Anh Dũng Avatar asked Oct 26 '25 14:10

Vũ Anh Dũng


1 Answers

Case 3 will not work with $text operator and reason is how Mongo Creates Text Indexes.

Mongo takes text indexed fields values and creates separate indexes for each unique word in string and not character(!).

so this means, that in your case for 1 object:

field name will have 2 indexes:

  • java
  • hut

field description will have 3 indexes:

  • coffee
  • and
  • cakes

$text operator compare $search values with this indexes and that's why "coff" will not work.

If you strongly want to take advantages of indexes you have to use $text operator, but it does not give you all flexibility, just like you want.

solution:

You Can simply use $regex with case sensitiveness option (i) and optimize your query with skip and limit.

If you want to return all documents and collection is large, $regex will cause performance issue

you can also check this article https://medium.com/coding-in-depth/full-text-search-part-1-how-to-create-mongodb-full-and-partial-text-search-c09c0bae17a3 and maybe use wildcard indexes for that, but i do not know is it a good practice or not.

like image 100
David Avatar answered Oct 29 '25 04:10

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!