mysqlsunspotsunspot-railssunspot-solrrsolr

Undefined field error in sunspot_solr grouping clause


I have product_details table which belongs to categories. product_details has fields like id, name, price, discount and category_id and categories table has fields like id and name. Am using mysql database Am trying to do group product details based on category_id. To do grouping i referred https://gist.github.com/f987013b2feec5b28456. But am getting error the following error

RSolr::Error::Http - 400 Bad Request
Error:     undefined field category_id

My model looks like this

    class ProductDetail < ActiveRecord::Base
      belongs_to :category

      searchable do
        text :name
        integer :category_id
      end

    end

My controller looks like this

def index
      @search_res1=ProductDetail.search do

        adjust_solr_params do |params|
          params[:group] = true
          params[:"group.field"] = "category_id"
          params[:"group.format"] = "simple"
        end

      end.execute
      @navurls=@search_res1.results
end

In my log file my getting like this

RSolr::Error::Http in ProductDetailsController#index

RSolr::Error::Http - 400 Bad Request
Error:     undefined field category_id

Request Data: "fq=type%3AProductDetail&fq=category_id_i%3A%281%29&start=0&rows=30&group=true&group.field=category_id&group.format=simple&q=%2A%3A%2A"

Backtrace: /home/toshiba/.rvm/gems/ruby-1.9.2-p290/gems/rsolr-1.0.8/lib/rsolr/client.rb:230:in `adapt_response'
/home/toshiba/.rvm/gems/ruby-1.9.2-p290/gems/rsolr-1.0.8/lib/rsolr/client.rb:167:in `execute'
/home/toshiba/.rvm/gems/ruby-1.9.2-p290/gems/rsolr-1.0.8/lib/rsolr/client.rb:161:in `send_and_receive' 

Please help me. Thank you.


Solution

  • Two things here:

    1.Grouping in Sunspot is only supported on string fields. So change your searchable block to the following:

    class ProductDetail < ActiveRecord::Base
      belongs_to :category
    
      searchable do
        text :name
        string :category_id_str do
          category_id.to_s
        end
      end
    end
    

    2.Change the group params to reflect the attribute name change:

    def index
      @search_res1=ProductDetail.search do
        adjust_solr_params do |params|
          params[:group] = true
          params[:"group.field"] = "category_id_str_s"
          params[:"group.format"] = "simple"
        end
      end.execute
      @navurls=@search_res1.results
    end
    

    I assume here the sunspot is adding on the extra _s to the attribute when it indexes it.