TikaのLanguageDetector

Tikaには文字列を渡すと、その言語を渡してくれる機能がある。使うためにはまずpom.xmlに以下の依存関係を追加する。

                <dependency>
                        <groupId>org.apache.tika</groupId>
                        <artifactId>tika-langdetect</artifactId>
                        <version>1.20</version>
                </dependency>

あとは、LanguageDetectorを生成して利用する。

import java.io.IOException;

import org.apache.tika.langdetect.OptimaizeLangDetector;
import org.apache.tika.language.detect.LanguageDetector;
import org.apache.tika.language.detect.LanguageResult;

public class LanguageDetectorExample {

    public String detectLanguage(String text) throws IOException {
        LanguageDetector detector = new OptimaizeLangDetector().loadModels();
        LanguageResult result = detector.detect(text);
        return result.getLanguage();
    }
}

上記はTikaにあるexampleコードだが、OptimaizeLangDetectorをnewして、loadModels()でLanguageDetectorを取得する。あとはLanguageDetectorに言語判定したいテキストを渡せば言語情報が返ってくる。

まぁ、とはいえ、そこそこ判定が外れる気もする…。

_sourceからデータを消しておく

クエリー時に_sourceに含めないという設定もあるけど、インデックス時に_sourceに入れないでおくという方法もある。Fess 13ではこの機能を使ってハイブリットな言語用インデックスで検索する予定ではある。

で、使うためにはElasticsearchのサイトにもあるような感じで

$ curl -X PUT "localhost:9200/fess" -H 'Content-Type: application/json' -d'
{
"mappings": {
"_doc": {
"_source": {
"excludes": [
"content_*",
"title_*"
]
}
}
}
}
'

のようにすれば、title_〜とcontent_〜のプロパティは_sourceに保存されなくなる。

でも、Fessではcontent_lengthは除外したくないので、

$ curl -X PUT "localhost:9200/fess" -H 'Content-Type: application/json' -d'
{
"mappings": {
"_doc": {
"_source": {
"includes": [
"content_length"
],
"excludes": [
"content_*",
"title_*"
]
}
}
}
}
'

としたところ、全部が消えることになり、期待する動きとは違っていた…。つまり、includes > excludesの順に処理するっぽい。というわけで、Fessではexcludesにワイルドカードを使わずに明示して対応した。