简体   繁体   中英

Grails / GORM withCriteria search toString()

I am displaying a table with User objects. The displayed information are:

User.firstName
User.lastName
User.email

but displayed by using user.toString() which results in the following output:

Gordon, Tomas (gordon.tomas@company.com)
Hanks, Jessica (hanks.jessica@company.com)

I want to have a filter on this list to allow people to search for specific users. These are the requirements:

1) 1 search field only
2) generic text input

currently i do the following to update the list, wheras owner is the input:

def user // input as string from the search field

def potentialUsers = User.withCriteria {
        or {
            ilike("firstName", '%' + user + '%')
            ilike("lastName", '%' + user + '%')
            ilike("email", '%' + user + '%')
        }
    }

this works very well when there is only 1 word of input.

what I however expect is that people will search like this:

  • 'tom'
  • 'gordon tomas'
  • 'jessica@company hanks'
  • 'tomas gordon'
  • ... and so on

the best solution in my eyes would be to search directly in toString() but I have not figured out how to do so..

any ideas on how to filter that correctly?

Basically you have 2 options here: do it quick or do it right.

Quick) add a field to your domain class to contain the concatenation of the field values you want to search, like User.concatenated = 'Gordon Tomas gordon.tomas@company.com' . then you can fire your search like:

def potentialUsers = User.withCriteria {
  user.split( /\s+/ ).each{  
    ilike 'concatenated', '%' + it + '%'
  }
}

Right) use Lucene or a Lucene -based proper full-text search framework, like hibernate-search or grails search plugin or elastic search to index your fields, so you can fire the complex multi-word queries

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