299 文字
1 分
Rails + MySQL 8でngramを用いたfulltext index
Railsのmigrationで普通にfulltext indexを付ける場合には以下のようにすると思いますが、普通のfulltext indexではngramが使われないので日本語の全文検索をする場合には全然マッチしません。
class AddNormalFullText < ActiveRecord::Migration[6.1] def change add_index :corporations, :name, :type => :fulltext endendngramのindexをつけるためには以下のように手でmigrationの内容を書く感じです。“ft_index”は自分でつけるindexの名称なので適当に付けてOK。
class AddNgramFullText < ActiveRecord::Migration[6.1] def up execute 'CREATE FULLTEXT INDEX ft_index ON corporations (name) WITH PARSER ngram' end def down execute 'ALTER TABLE corporations DROP INDEX ft_index' endendshow create tableをすれば、以下のようなindexが作られることが確認できます。
FULLTEXT KEY `ft_index` (`name`) /*!50100 WITH PARSER `ngram` */MySQL 5.7系でも同じだと思います。
パフォーマンスはなんか、いまいちです。平均約10文字のカラムに対して500万レコードを対象にindexを張りました。2件を抽出するために3秒位かかりました。
別の語句で試したら0.5秒以内には返ってきたりします。
ngram周りのパラメータはデフォルトです。
Rails + MySQL 8でngramを用いたfulltext index
https://blog.teraren.com/posts/rails-mysql-ngram-fulltext/