What part of this Solr-Sunspot setup am I missing?

2019-07-22 01:41发布

I thought I had this down piece-of-cake .. but anytime I do a query on any keyword it doesn't load any tables from SQL. I get no errors.

user.rb

searchable do
  string  :first_name
  string  :last_name
  string  :name
  string  :email
  time    :created_at
end

users_controller.rb

class Admin::UsersController < Admin::ApplicationController

  def index
    s = Sunspot.search User do |query|
      query.keywords params[:q]
      query.any_of do |any_of|
        any_of.with(:first_name)
        any_of.with(:first_name)
        any_of.with(:email)
        any_of.with(:name)
      end
      query.paginate :page => (params[:page] && params[:page].to_i || 1), :per_page => 20
      query.order_by('created_at', 'desc')
    end

    s.execute!
    @users = s.results

    render :action => 'index'
  end

Then I ran:

$> script/console
$> User.reindex

When I make no search at all..it successfully displays all User results

I believe I am to make all those string tags into text tags but that returns this error:

Sunspot::UnrecognizedFieldError in Admin/usersController#index

No field configured for User with name 'first_name'

What am I missing to get this to respond to keywords?

2条回答
Animai°情兽
2楼-- · 2019-07-22 02:17

(A more complete explanation for your own self-followup.)

Regarding your setup:

searchable do
  string  :first_name
  string  :last_name
  string  :name
  string  :email
  time    :created_at
end

A string in Solr is intended to be used for exact matches. It isn't pre-processed or tokenized the way a text column would be. These literal matches are used for filtering ("where category_name equals 'Sale'"), faceting, sorting, and so on.

You more likely want text fields. Text fields are tokenized with the Standard Tokenizer, lowercased with the LowerCase Filter, and have their dots and apostrophes removed with the Standard Filter among many other potential options.

When people think of the functionality of Solr's full-text search, they're thinking of how it processes text fields.

Furthermore, Sunspot's keywords search method by default searches against all of your text fields, which explains why you aren't getting results when you include keywords -- your documents have no text fields to search against.

As you note in your self-followup, you'll want to switch to text fields to get the results you're expecting.

查看更多
smile是对你的礼貌
3楼-- · 2019-07-22 02:29

This is not exactly the nicest answer, but I find that combining the strings and text tags together it works. So my User model looks like this :

searchable do
  text  :first_name
  text  :last_name
  text  :name
  text  :email
  time  :created_at
  string :first_name
  string :last_name
  string :name
  string :email
end
查看更多
登录 后发表回答