Elasticsearch

[Elasticsearch] 한글 분석기를 이용한 실전 인덱싱 & 검색

Jack Moon 2015. 8. 25. 17:08

한글 구문분석기 은전한닢을 적용하여 1000개 정도의 뉴스기사를 인덱싱해 보도록 하겠습니다.


과정

1. 인덱스 생성

2. 저장할 json 파일 생성

3. 검색



1. 인텍스 생성

curl -XPUT 'http://localhost:9200/news' -d '

{

  "settings" : {

    "analysis" : {

      "analyzer" : {

        "korean_analyzer" : {

            "type":"custom",

            "tokenizer":"mecab_ko_standard_tokenizer"

        }

      }

    }

  }

}'

이렇게 news 인덱스를 생성하여 한글을 입력하니 한글 분석기가 적용이 안되더군요.

mapping에서 적용해줘야 한글 분석기가 적용됩니다.


curl -XPUT 'http://localhost:9200/news' -d '

{

  "settings" : {

    "analysis" : {

      "analyzer" : {

        "korean_analyzer" : {

            "type":"custom",

            "tokenizer":"mecab_ko_standard_tokenizer"

        }

      }

    }

  },

  "mappings" : {

    "news1" : {

      "properties" : {

        "title" : { "type" : "string", "index_analyzer" : "korean_analyzer" },

        "link" : { "type" : "string" },

"media" : { "type" : "string" },

        "datetime" : { "type" : "date" },

        "stamp" : { "type" : "long" }

      }

    }

  }

}'



2. 저장할 json 파일 생성



test.txt

php로 간단하게 작성해 봤습니다. 

DB에 euc-kr로 저장되어 있어 utf-8로 변경했고, PHP 버전 5.16이라 json 라이브러리를 사용했습니다. 

https://github.com/alexmuz/php-json


json_test.php


<?

require_once("/usr/local/test/php-json/json_encode.php");

//require_once("json_decode.php");


function mysql_open(){

$p_username = "user";

$p_password = "password";

$host = "host";

$db = "DB";


$connect  =  mysql_connect( $host, $p_username, $p_password)  or die( "MySQL SQL server에 연결할 수 없습니다.");

mysql_select_db($db,$connect); 

return $connect; 

}


$conn = mysql_open();

$sql = "SELECT titlestr, linkstr, mediastr FROM tbnews LIMIT 1000";

$rs = mysql_query($sql) OR die(__FILE__." : Line ".__LINE__."<p>".mysql_error());



for($i=0; ($row = mysql_fetch_row($rs)); $i++) {


$titlestr = iconv('CP949','utf-8//IGNORE',$row[0]);

$linkstr = $row[1];

$mediastr = iconv('CP949','utf-8//IGNORE',$row[2]);

$arrayData[$i] = array("title"=>$titlestr,

"media"=>$mediastr,

"link"=>$linkstr);

}


$cont = "";

foreach($arrayData as $key=>$val) {

$cont .= '{ "index" : { "_index": "news", "_type": "news1"} }';

$cont .= "\n";

$cont .= json_encode($arrayData[$key]);

$cont .= "\n";

}


mysql_close($conn);



$filename = 'test.txt';


if (!$handle = fopen($filename, 'a')) {

echo "Cannot open file ($filename)";

exit;

}


if (fwrite($handle, $cont) === FALSE) {

echo "Cannot write to file ($filename)";

exit;

}


fclose($handle);



?>

 

3. 검색


curl 'localhost:9200/news/_search?pretty' -d '

{

  "query" : {

    "match" : {

      "title" : {

        "query" : "금융"

      }

    }

  }

}'



test.txt
4.36MB