简体   繁体   中英

Is there a similar method in the Grails GORM MongoDB plugin like the searchable search() method?

I was using the Grails Searchable plugin and now we've switched to the GORM MongoDB plugin. The Searchable plugin has a method search() that allows searching all fields using boolean connectors and wild-cards. Is there a similar method in the Grails GORM MongoDB plugin?

If not, what would be the best practices to create a similar method?

Searchable, as well as the Elasticsearch plugin seem to rely on the Hibernate plugin and do not work with the MongoDB GORM. I implemented a simple search service for Mongo using the low-level API, and the mongo '$regex' operator :

Here is an example of search on the 'content' property of a domain class named "Page"

class SearchService {
  static transactional = false
   def query(String query){
    return Page.collection.find( ['content':['$regex':query, '$options': 'i']]).collect({
      it as Page
    })

  }
}

Basically the regex search as mentioned by Lucas T is the best way to build a flexible search but I would not recommend the use of the ignore case regex search ('$options': 'i'). When using ignore case mongodb cannot make use of indexes and has to check each single document which results in poor performance.

My approach is to add a new field to the document where you store normalized search keywords for each document. I usually normalize keywords by lowering the case and stripping out characters which are difficult to handle in regexes - the latter depends on your data and query needs. Regex match against the beginning uses the index more efficient, too.

See at the end of the page: http://docs.mongodb.org/manual/reference/operator/regex/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM