Sql 在大句中搜索字符串时优化查询的最佳方法

Sql 在大句中搜索字符串时优化查询的最佳方法,sql,ruby-on-rails,ruby,ruby-on-rails-3,sqlite,Sql,Ruby On Rails,Ruby,Ruby On Rails 3,Sqlite,我有如下要求 诗属于诗人 这位诗人有许多诗 如果用户搜索单词“ruby” 应该给, 所有诗歌中使用单词ruby的总次数 words.each do |word| count += 1 if word.upcase.include?(word.upcase) end 展示所有有红宝石这个词的诗 每首诗中使用ruby一词的次数 使用红宝石这个词的诗人总数 每位诗人使用“红宝石”一词的总次数 所以我在范本诗中的疑问就在这里 poems= where(&

我有如下要求

诗属于诗人

这位诗人有许多诗

如果用户搜索单词“ruby”

应该给,

所有诗歌中使用单词ruby的总次数

      words.each do |word|
        count += 1 if word.upcase.include?(word.upcase)
      end
展示所有有红宝石这个词的诗

每首诗中使用ruby一词的次数

使用红宝石这个词的诗人总数

每位诗人使用“红宝石”一词的总次数

所以我在范本诗中的疑问就在这里

    poems= where("poem_column like ?", "%#{word}%" )
    @results = {}
    poems.each do |poem|
      words = poem.poem_column.split
      count = 0
      words.each do |word|
        count += 1 if word.upcase.include?(word.upcase)
      end
      @results[poem] = count # to get each poem using word ruby
    end
为了让诗人计数 诗中模式

   @poets = poems.select("distinct(poet_id)")
      @poets.each do |poet|
        @poets_word_count << poems.where("poet_id = #{poem.poet_id}").count
      end
你们中有谁能告诉我优化它的方法吗?由于缺乏查询方面的知识,我无法用任何其他方法来优化它


提前感谢

我的建议,您可以更改从您的帖子中引用的以下代码:

poems.each do |poem|
  words = poem.poem_column.split
  count = 0
  words.each do |word|
    count += 1 if word.upcase.include?(word.upcase)
  end
  @results[poem] = count # to get each poem using word ruby
end
致:


不是答案,只是测试。

首先,在保存每首诗时减少其数据提取关键字:

rails g resource Keyword word occurrences poem_id:integer
rails db:migrate
然后在你的诗歌模型中:

# add more words
EXCLUDED_WORDS = %w( the a an so that this these those )

has_many :keywords

before_save :set_keywords

# { :some => 3, :word => 2, :another => 1}
def keywords_hash(how_many = 5)
  words = Hash.new 0
  poem_column.split.each do |word|
    words[word] += 1 if not word.in? EXCLUDED_WORDS
  end
  Hash[words.sort { |w, w1| w1 <=> w }.take(how_many)]
end

def set_keywords
  keywords_hash.each do | word, occurrences |
    keywords.create :word => word, :occurrences => occurrences
  end
end
然后,当您有单词要搜索时:

keywords = Keyword.where(word: word)
poems = keywords.poems
poets = poems.poets
要使用最后一部分,您需要在
Poem
模型中:

belongs_to :poem

def self.poem_ids
  includes(:poem).map(&:poem_id)
end

def self.poems
  Poem.where(id: poem_ids)
end
def self.poet_ids
  includes(:poet).map(&:poet_id)
end

def self.poets
  Poet.where(id: poet_ids)
end
在我看来,这种方法只需要3个查询,没有连接,所以它似乎是有意义的


我将考虑如何扩展这种方式,通过整个内容进行搜索。

你知道在哪里花费的时间最多:找诗人吗?正在获取poem_列中搜索词的出现次数?两者都需要时间,但poem_列中的搜索词需要更多时间。[poem列最多包含20行]请考虑使用。它没有任何区别:-(唯一的问题是数据库问题,因为我们必须存储每个单词的信息,否则会减少时间。再次感谢并欢呼关键字表将有数百万个dataSQLite全文搜索,在@LS_dev comment中更有意义。我正要建议切换到更常见的生产数据库并使用全文搜索,如PostgreSQL并使用
pgu搜索
gem。
def self.poet_ids
  includes(:poet).map(&:poet_id)
end

def self.poets
  Poet.where(id: poet_ids)
end