Sunday 27 April 2014

Searchable plugin: Search by a domain relationship

I don't remember last time I used Searchable Plugin, there must be like a year or so. Anyway I was trying to map a Product/I18nProductDescription domain classes to be able to search by the product description and then return the product id in order to build the link to the product detail.
I was using the default configuration and doing the queries through searchable controller to test my mappings. These were the initial mappings:
class Product {

    static hasMany = [descriptions: I18NDescription]   

}

class I18nDescription {

   static belongsTo = [product: Product]
   static searchable = true

   Locale locale
   String title
   String description

}

The problem was that if you map as "searchable" only I18nDescription, the index doesn't store the relationship, then you won't be able to do "productDescription.product.id" and you'll get a NPE (I guess this is caused because instances are not taken from the hibernate session but from lucene index).

I read the documentation and I found the "component" term.

class Product {

   static hasMany = [descriptions: I18NDescription]   
   static searchable = {
      descriptions component: true
   }

}

class I18nDescription {

   static belongsTo = [product: Product]
   static searchable = {
      product component: true
   }

   Locale locale
   String title
   String description

}


So I mapped my to domain classes as components of each other. But if I stopped there I would get double of results, because both domain classes are pointing to each other right? So I need to "disable" for searching one of them. To do so, one of them should have an option to tell it's not going to have it's one index but is going to be part of another search index.

class Product {

   static hasMany = [descriptions: I18NDescription]   
   static searchable = {
      descriptions component: true
      mapping {
        root false
      }
   }

}

class I18nDescription {

   static belongsTo = [product: Product]
   static searchable = {
      product component: true
      mapping {
        root true
      }
   }

   Locale locale
   String title
   String description

}

That way you can search by title or description and be able to get the reference of the product without having to do anything else.

References

1 comment:

  1. Oracle fusion financials online training institute we have our branch over all the india.
    Oracle Fusion Cloud HCM Online Training in Hyderabad, Bangalore, Delhi, Chennai, Kolkata, Pune,
    Mumbai, Ahmedabad, Gurgon, Noida, India, Dubai, UAE, USA, Kuwait, UK, Singapore, Saudi Arabia,
    Canada, Oracle Fusion HCM Online Training

    Oracle Fusion Cloud HCM Training

    ReplyDelete