8 Example - Reference Documentation
Authors: Manuarii Stein, Stephane Maldini, Serge P. Nekoval
Version: 0.18.7.1-SNAPSHOT
8 Example
The domains
class Tweet { static searchable = { message boost:2.0 } static belongsTo = [ user:User ] static hasMany = [ tags:Tag ] static constraints = { tags nullable:true, cascade:'save, update' } String message = '' Date dateCreated = new Date() }
class User { static searchable = { except = 'password' lastname boost:20 firstname boost:15, index:'not_analyzed' listOfThings index:'no' someThings index:'no' tweets component:true } static constraints = { tweets cascade:'all' } static hasMany = [ tweets:Tweet ] static mappedBy = [ tweets:'user' ] String lastname String firstname String password String activity = 'Evildoer' String someThings = 'something' ArrayList<String> listOfThings = ['this', 'that', 'andthis'] }
class Tag { static searchable = { except=['boostValue'] } String name Integer boostValue = 1 }
The controller
A action triggering indexation
ElasticSearchController
(testCaseService
is just dealing with GORM instructions):
class ElasticSearchController { def elasticSearchService def testCaseService def postTweet = { if(!params.user?.id) { flash.notice = "No user selected." redirect(action: 'index') return } User u = User.get(params.user.id) if (!u) { flash.notice = "User not found" redirect(action: 'index') return } // Create tweet testCaseService.addTweet(params.tweet?.message, u, params.tags) flash.notice = "Tweet posted" redirect(action: 'index') } }
User
in the database), new Tweets will be indexed automatically,
and corresponding User
indexed documents will be updated since we have set the tweets
association as component.Searching for Tweets
def searchForUserTweets = { def tweets = Tweet.search("${params.message.search}").searchResults def tweetsMsg = 'Messages : ' tweets.each { tweetsMsg += "<br />Tweet from ${it.user?.firstname} ${it.user?.lastname} : ${it.message} " tweetsMsg += "(tags : ${it.tags?.collect{t -> t.name}})" } flash.notice = tweetsMsg redirect(action: 'index') }
Searching for anything
def searchAll = { def res = elasticSearchService.search("${params.query}").searchResults def resMsg = '<strong>Global search result(s):</strong><br />' res.each { switch(it){ case Tag: resMsg += "<strong>Tag</strong> ${it.name}<br />" break case Tweet: resMsg += "<strong>Tweet</strong> "${it.message}" from ${it.user.firstname} ${it.user.lastname}<br />" break case User: resMsg += "<strong>User</strong> ${it.firstname} ${it.lastname}<br />" break default: resMsg += "<strong>Other</strong> ${it}<br />" break } } flash.notice = resMsg redirect(action:'index') }