Searchkick: Facets for HasMany Associations

Created on 5 Dec 2013  路  9Comments  路  Source: ankane/searchkick

Hey guys,

i have a project model:

  Project < ActiveRecord::Base
     searchkick

     has_many :categories_has_projects
     has_many :categories, through: :categories_has_projects

 end

and category model:

  Category < ActiveRecord::Base

     has_many :categories_has_projects
     has_many :projects, through: :categories_has_projects

 end

how can i search and declare facets for categories through Project model?

for exemple:

  search = Project.search 'something', 
    facets: [:categories_title] #pseudo code

  # in order to have this in my view
  # sidebar
  # category_A (3) 
  # category_B (5)
  # category_C (3)


Most helpful comment

Searchkick won't know unless you tell it. See https://github.com/ankane/searchkick#associations

All 9 comments

Add the category titles to the search_data method.

class Project < ActiveRecord::Base
  def search_data
    attributes.merge(
      categories_title: categories.map(&:title)
    )
  end
end

Project.reindex and your search code above should work.

thanks, it worked :+1:

Is it possible to do autocomplete and suggestions as well? I had tried doing so with

Taken from the example above, i had tried -
autocomplete: [ 'categories_title'], suggest: [ 'categories_title' ] with no luck.

@ankane what would the syntax look like if I wanted to index both the name and ID columns of an associated model?

@cmalpeli You should be able to use dot notation, like categories.id, if you index as:

def search_data
  {
    categories: categories.as_json(only: [:id, :name])
  }
end

This is relatively untested, but happy to accept a PR if further support is needed.

Thanks @ankane that seems to work!

Follow up, what would be the proper syntax for setting up both aggregations and where clauses matching only the category name now that it's in a nested structure?

"categories": [
                  {
                     "id": 749,
                     "name": "Agile"
                  },
                  {
                     "id": 15,
                     "name": "DevOps"
                  }]

You should be able to use dot notation for those as well.

@ankane I'm wondering if nested object was updated, such as category's name was changed, will searchkick update data of the project in elasticsearch too?

Searchkick won't know unless you tell it. See https://github.com/ankane/searchkick#associations

Was this page helpful?
0 / 5 - 0 ratings

Related issues

netwire88 picture netwire88  路  3Comments

jnimety picture jnimety  路  4Comments

namila picture namila  路  4Comments

JensDebergh picture JensDebergh  路  4Comments

matthewmoss picture matthewmoss  路  4Comments