Search code examples
grailspluginssearchable

Grails - Make searches with different fields


I'm using Grails 2.3.x and the Searchable plugin,

Imagine the next domain class book (String Author, String Title, Date pubDate);

I need to make a search with different fields, for example;

I want to search the books with a publication date (pubDate) between Field1: 03/03/2014 and Field2: 04/04/2014, also for example: the books with the title X and pubDate between Field1: 03/03/2014 and Field2: 04/04/2014

Is anyway to do a search with different parameters with the searchable plugin?

Thank you very much.

EDIT: Where do I need to write that code?
def search = {
...
Book.search {
gt("pubDate", field1) lt("pubDate", field2)
}
}


Solution

  • Searchable provides a search builder that should accomplish this. You can do your searches like this:

    Book.search {
        gt("pubDate", field1)
        lt("pubDate", field2)
    }
    

    and

    Book.search {
        term("title", x)
        gt("pubDate", field1)
        lt("pubDate", field2)
    }
    

    That code will search the index for all Book objects that meet the criteria and return a List those Books. You can put that in your controller or in a service. For instance, here is what it would look like in a controller action:

    def searchBooks(String title, Date pubDate) {
        def books = Book.search(result: 'every') {
            term('title', title)
            gt('pubDate', pubDate)    
        }
    
        render view: 'list', [bookList: books]
    }
    

    See this doc: http://grails.org/Searchable+Plugin+-+Searching+-+Query+Builder