Tuesday, February 21, 2012

Searching Multiple Data Sources in Grails

Have you got domain classes mapped to multiple datasources? The Searchable plugin will mysteriously not be building indexes for domain classes in your secondary datasources by default. The following explains a way to change the behavior.

This is taken from my personal experience, and information compiled from a helpful thread archived on Grails, found here. We are going to need to redefine some beans.

Step 1:
Open conf/spring/resources.groovy

add in the following bean:

import org.compass.gps.device.hibernate.HibernateGpsDevice //need this import for new datasource
import grails.plugin.searchable.internal.compass.config.SessionFactoryLookup //need this import to get correct sessionfactory class

beans = {

/* ~ your other beans here */

compassGpsDevice(HibernateGpsDevice) { bean ->
bean.destroyMethod = "stop"
name = "hibernate"
sessionFactory = { SessionFactoryLookup sfl ->
sessionFactory = ref('sessionFactory_datasourceName') 
}//replace datasourceName with the name of the datasource as defined in conf/DataSource.groovy
fetchCount = 5000

Step 2:
You could stop here if this was the only datasource that contained indexable classes, but continue to add each compassGPSdevices for each additional datasource (including the default), making sure they are unique names ie:

anotherUniquecompassGpsDevice(HibernateGpsDevice) { bean ->
bean.destroyMethod = "stop"
name = "unqiueHibernateName"
{ SessionFactoryLookup sfl ->
sessionFactory = ref('sessionFactory_uniquedatasource') 
fetchCount = 5000

then finally we need to combine all of these datasources into one SingleCompassGps for searchable. Add this last bean:

import org.compass.gps.impl.SingleCompassGps

compassGps(SingleCompassGps) {
compass = ref('compass')
gpsDevices = [compassGpsDevice, anotherUniqueCompassGpsDevice /* ~add the other sources in here */ ]

Thanks to the original thread for guidance. Hopefully this compilation of guidance will help someone else save some time. The major additions beyond the original thread are to use the sessionfactorylookup. You can see these objects in SearchableGrailsPlugin.groovy - we are simply re defining them with new datasources!

1 comment:

  1. oh, yes... you save me... i'm using latest searchable 0.6.6 and grails 2.3.4 :)
    I did a spanish version of your post http://blog.soluciones3f.com.ar/2013/12/10/grails-searchable-con-no-orm-y-varios-datasource/