meilisearch / meilisearch-rails

Meilisearch integration for Ruby on Rails
https://www.meilisearch.com
MIT License
295 stars 48 forks source link

single index sharing didnt create new index. #338

Closed botbotbotbotboot closed 6 months ago

botbotbotbotboot commented 6 months ago

Description Following docs i created a shared index as below:

class Answer < ApplicationRecord
  include MeiliSearch::Rails

  meilisearch index_uid: "Discussion", primary_key: :ms_id

  belongs_to :question
  meilisearch do
    attribute :title
    attribute :body
  end

  def ms_id
    "answer_#{primary_key}"
  end
end
class Question < ApplicationRecord
  include MeiliSearch::Rails
  meilisearch index_uid: "Discussion", primary_key: :ms_id
  has_many :answers

  meilisearch do
    attribute :title
    attribute :body
  end

   def ms_id
    "question_#{primary_key}"
  end
end

Expected behavior That it will create new index "Discussion"

Current behavior Did not create new Index.

Screenshots or Logs Its ignoring the configuration.

Environment (please complete the following information):

ellnix commented 6 months ago

Please only call meilisearch once in models and append the block to that one call:

class Answer < ApplicationRecord
  include MeiliSearch::Rails
  belongs_to :question

  meilisearch index_uid: "Discussion", primary_key: :ms_id do
    attribute :title
    attribute :body
  end

  def ms_id
    "answer_#{primary_key}"
  end
end
class Question < ApplicationRecord
  include MeiliSearch::Rails
  has_many :answers

  meilisearch index_uid: "Discussion", primary_key: :ms_id do
    attribute :title
    attribute :body
  end

   def ms_id
    "question_#{primary_key}"
  end
end

I believe the second call to meilisearch was overwriting the first. Please let me know if this fixes it :smile:.

botbotbotbotboot commented 6 months ago
class Question < ApplicationRecord
  include MeiliSearch::Rails
  has_many :answers

  meilisearch index_uid: "Discussion", primary_key: :ms_id do
    attribute :title
    attribute :body
  end

   def ms_id
    "question_#{id}"
  end
end

Ok this worked!. Thank you.

Now, i can search by Question.search() and it will query both models right?

ellnix commented 6 months ago

Now, i can search by Question.search() and it will query both models right?

I have to apologize, I thought you could but it turns out that is not what the gem does. Please use this as a temporary fix (replace QUERY_HERE with the search query):

Question.index.search(QUERY_HERE)['hits'].map do |result|
  klass, id = result['ms_id'].split('_')
  case klass
  when 'question'
    Question.find(id)
  when 'answer'
    Answer.find(id)
  end
end

I have to make some proposals to make the straightforward Question.search work.