LoginSignup
2
1

More than 5 years have passed since last update.

elastic4sでカタカナ、ローマ字を使う

Posted at

インデックス作成するときにカタカナとかローマ字に変換してしまえばユーザがカタカナとか入力した時でもヒットさせることができます。

使うのはkuromoji_readingformです

use_romajiでカタカナとローマ字を切り替えることができます。

elastic4sのDSLで使えるようにするためにKuromojiReadingformを作成します。

import org.elasticsearch.common.xcontent.XContentBuilder
import com.sksamuel.elastic4s.analyzers.TokenFilter

import com.sksamuel.elastic4s.analyzers.TokenFilterDefinition

case class KuromojiReadingform(name: String, userRomaji: Boolean) extends TokenFilterDefinition {
  val filterType = "kuromoji_readingform"

  override def build(source: XContentBuilder): Unit = {
    source.field("use_romaji", userRomaji)
  }
}

object KuromojiReadingform {
  def apply(name: String, userRomaji: Boolean) = new KuromojiReadingform(name, userRomaji)
}

あとはマッピングを定義して

createIndex("bands").mappings(
  mapping("artist") as (
    textField("name"),
    textField("description") analyzer "my_analyzer"
  )
)
  .analysis(
    CustomAnalyzerDefinition(
      "my_analyzer",
      KuromojiTokenizer,
      KuromojiReadingform("kuromoji_kana_filter", userRomaji)
    )
  )

analyze投げるとカタカナかローマ字に変換されているのがわかります。

val response: AnalyzeResponse = client.java.admin().indices().analyze(new AnalyzeRequest("bands").analyzer("my_analyzer").text("働きたくない")).actionGet()
response.forEach { token =>
  {
    println(s"""
  |token: ${token.getTerm()}
  |start_offset: ${token.getStartOffset()}
  |end_offset: ${token.getEndOffset()}
  |type: ${token.getType}
  |position: ${token.getPosition}
  """.stripMargin)
  }
}

出力結果
useRomajiがtrueの場合

token: hataraki
start_offset: 0
end_offset: 2
type: word
position: 0


token: taku
start_offset: 2
end_offset: 4
type: word
position: 1


token: nai
start_offset: 4
end_offset: 6
type: word
position: 2

userRomajiがfalseの場合

token: ハタラキ
start_offset: 0
end_offset: 2
type: word
position: 0


token: タク
start_offset: 2
end_offset: 4
type: word
position: 1


token: ナイ
start_offset: 4
end_offset: 6
type: word
position: 2

完全なコードはこちら

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1