ElasticSearchを使ってる時に、このトークナイズを外部データで使えたらいいなぁと思っていて、色々調べました。ElasticSearchにデータを入れないで、外で分割して、ほんでMySQLに蓄積したりできたらいいなと思って。作ってみました

今回のゴール

以下のようなことをやりたいと思っています

http://{host}/analyzer.php?word=%E3%81%99%E3%82%82%E3%82%82%E3%82%82%E6%A1%83%E3%82%82%E6%A1%83%E3%81%AE%E3%81%86%E3%81%A1

///以下、結果
{"detail":{"custom_analyzer":false,"analyzer":{"name":"org.apache.lucene.analysis.ja.JapaneseAnalyzer","tokens":[{"token":"すもも","start_offset":0,"end_offset":3,"type":"word","position":0,"baseForm":null,"bytes":"[e3 81 99 e3 82 82 e3 82 82]","inflectionForm":null,"inflectionForm (en)":null,"inflectionType":null,"inflectionType (en)":null,"keyword":false,"partOfSpeech":"名詞-一般","partOfSpeech (en)":"noun-common","positionLength":1,"pronunciation":"スモモ","pronunciation (en)":"sumomo","reading":"スモモ","reading (en)":"sumomo","termFrequency":1},{"token":"桃","start_offset":4,"end_offset":5,"type":"word","position":2,"baseForm":null,"bytes":"[e6 a1 83]","inflectionForm":null,"inflectionForm (en)":null,"inflectionType":null,"inflectionType (en)":null,"keyword":false,"partOfSpeech":"名詞-一般","partOfSpeech (en)":"noun-common","positionLength":1,"pronunciation":"モモ","pronunciation (en)":"momo","reading":"モモ","reading (en)":"momo","termFrequency":1},{"token":"桃","start_offset":6,"end_offset":7,"type":"word","position":4,"baseForm":null,"bytes":"[e6 a1 83]","inflectionForm":null,"inflectionForm (en)":null,"inflectionType":null,"inflectionType (en)":null,"keyword":false,"partOfSpeech":"名詞-一般","partOfSpeech (en)":"noun-common","positionLength":1,"pronunciation":"モモ","pronunciation (en)":"momo","reading":"モモ","reading (en)":"momo","termFrequency":1}]}}}

まぁ、接続詞とかは、カットされてますが、とはいえ、文章にどんな主要ワードが入ってるか?は十分わかるので、これでいいとして。ともかく、これを使って別のデータベースとかに活用したいと思ったのです。

apiを叩いてみる

かなりざっくりですが、以下のような感じで実現自体は可能でした。ついでに、パラメータにprettyをつけたら、pretty printになるといいと思ったので、そこもつけてみました

///パラメータのwordに文章が指定されてるかチェック
if(isset($_GET["word"])&&$_GET["word"]!=""){

        ///prettyかどうかの分岐
        if(isset($_GET["pretty"])){
                $url='http://{host}:9200/_analyze?pretty';
        }else{
                $url='http://{host}:9200/_analyze';
        }

        $header= array(
                "Content-Type: application/json"
        );
        $data_array["analyzer"]='kuromoji';
        $data_array["text"]=$_GET["word"];
        $data_array["explain"]=true;

        $json=json_encode($data_array);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl,CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
        $res = curl_exec($curl);

        curl_close($curl);
        header('Content-type: application/json');
        echo $res;

}

ひとまずメモがてら

コメント