SearchKick:仅字段直接映射时是否需使用search_data?
search_data vs Just searchable? Great question! Let's break this down based on your exact model setup and search requirements:
1. Author Model Scenario (Search by Author's name)
If your only need is to search for Author records using their name field, and you don't need to transform, combine, or add any extra data to what's already in the model, you don't need search_data. Just defining the searchable attribute is totally sufficient.
Here's what that would look like:
class Author < ApplicationRecord searchkick searchable: [:name] end
Searchkick will automatically sync the name field directly to Elasticsearch, creating a direct mapping between your model's field and the ES document field. This works perfectly for your requirement of searching Authors by their name.
2. Book Model Scenario (Search by Book's name or Author's name)
This is where things change. Since you need to include the associated Author's name in your Book search index, you do need to use search_data. By default, Searchkick doesn't automatically index fields from associated models—you have to explicitly include them via the search_data method.
Here's how you'd set this up:
class Book < ApplicationRecord belongs_to :author searchkick searchable: [:name, :author_name] def search_data { name: name, author_name: author.name # Pull in the associated Author's name } end end
This method tells Searchkick to create an ES document for each Book that includes both the Book's own name and the linked Author's name (stored as author_name in the index). Now you can search Books by either field seamlessly.
General Rule of Thumb
- Skip
search_datawhen: You're only indexing direct model fields with no transformations, and no associated model fields need to be included in the search index. - Use
search_datawhen: You need to include associated model fields, compute derived values (like a full name from first/last), format fields (e.g., adjust date formats), or combine multiple fields into one for better searchability.
内容的提问来源于stack exchange,提问作者s_dolan

