开发者

Grails search mechanism

For my website, i need to do a search mechanism, in which some of the entry field would be: Country, City, Between Dates (with or without year field), Keywords, etc etc.

My problem is, the user must decide what they wanna search for. For example, if they want to introduce just date, or date and city, or city and keyword.. etc. I dont really know how to do that, i mean, i know how to search for one thing at a time, but i'm not sure how can do this all-in-one.

a) Would i need like something like this: (if-else, if-else) and than write the code for each combination, or there is an easier way to do that?

b )Bytheway, my search mechanism is done the folowing way (i'v never done a search mechanism before, so i dont know if it is the best aproach, would apreciate some comments here also and suggestions):

  class book{
    String a
    String b
    ...
    Date z

    String allAttributesTogether() {
    a + b + c + ... + z
    }

    }

then in my controller, i do a double for statment and cross-match the 开发者_如何学Cintroduced words for the search and the result of allAttributesTogether().

Thanks in advanced, VA


Check out the filter pane plugin.


When you say "search", comes to my mind search engines. But I think you are asking about querying the database, right?

If you are talking about search mechanisms, search engines are a great tool. You can take a look at Lucene, Compass, and ElasticSearch (ES) to name a few. Compass and ES are based on lucene, but are much higher in the abstraction level (easier to use). I have been using ElasticSearch with great satisfaction.

If you are talking about querying the database, then you can just build a HQL query dynamically. The method bellow should be in a Controller, as it uses the params attribute. It is not tested ok?

List allAttributesTogether() {
    def query = " select book from Book book "
    def queryParams = [:]
    def needsAnd = false

    if(params.a || params.b || params.z ){
       query += " where "
    }
    if(params.a){
       query += " book.a = :a "
       queryParams['a'] = params.a
       needsAnd = true
    }
    if(params.b){
       if(needsAnd) query += " and "
       query += " book.b = :b "
       queryParams['b'] = params.b
       needsAnd = true
    }
    if(params.a){
       if(needsAnd) query += " and "
       query += " book.z = :z "
       queryParams['z'] = params.z
    }

    return Book.executeQuery(query, queryParams)

}

There is also the alternative of using Criteria builder. You can also use "if" to add clauses to your Criteria clauses.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜