S2JDBC から Amazon RDS の MySQL を UTF-8 で扱うには

Amazon RDS を初めて使って、文字化けからなかなか解放されなかったので、メモしておく。 DB Parameter Group の作成 まず、Amazon RDS には DB Parameter Group という設定グループがある。my.cnf に定義するような設定はこのグループに対して適用する。 DB Parameter Group に Character 関係の設定を UTF-8 にしたものを作っておき、DBインスタンスに適用する。 S2JDBC これはS2JDBCというより、JDBC URLの設定だが characterEncoding=UTF-8 を付加する。 テーブル作成時に文字コード](http://d.hatena.ne.jp/keyword/%CA%B8%BB%FA%A5%B3%A1%BC%A5%C9)を指定 CREATE TABLE に DEFAULT CHARSET=utf8 を指定する。 ※ちなみに MySQL のテーブル名は普通に使うと大文字小文字の区別がいるため、Entity クラスに @Table(name=小文字) のアノテーションを定義しておく。

2010年8月13日 · Toshimitsu Takahashi

MySQL で後からユニークインデックスを追加するには

フィールドを Unique にする方法 mysql> alter table 対象テーブル add unique (対象フィールド); 作業ログ(フィールドサイズが 999 バイトを超えていたら) 今回 support テーブルの uri フィールドをユニーク化しようとしたが、 mysql> alter table support add unique (uri); ERROR 1071 (42000): Specified key was too long; max key length is 999 bytes となってしまった。定義を調べると、 mysql> show fields from support; +---------+---------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | uri | varchar(512) | NO | MUL | | | | title | varchar(1024) | NO | MUL | | | | content | mediumtext | YES | | NULL | | | updated | timestamp | NO | | CURRENT_TIMESTAMP | | +---------+---------------+------+-----+-------------------+----------------+ 512だが、UTF-8なので超えてしまっているのだろう。 実際には数文字しか入っていないので別のフィールド uri2 を作って、そこに値をコピーしてからユニーク化して、元の列を削除してリネームすることにした。 127なら4倍しても999バイトには届かないので、varchar(127) で定義する。 ...

2008年2月9日 · Toshimitsu Takahashi

MeCab + Senna + Tritonn で MySQL 全文検索を試す(2)

MeCab + Senna + Tritonn で MySQL 全文検索を試す - Tosshi Note の続き Google 風の検索 UI を実装してみた。 テーブルを作成 - SQL 1 2 3 4 5 6 7 8 9 CREATE TABLE fastsearch ( id INTEGER AUTO_INCREMENT, PRIMARY KEY (id), uri VARCHAR(512) NOT NULL, title VARCHAR(1024) NOT NULL, content MEDIUMTEXT, FULLTEXT INDEX USING NGRAM, SECTIONALIZE (title, content) ) DEFAULT CHARSET utf8 ENGINE = MyISAM; ※USING NGRAM をはずせば、MeCab の形態素解析になる。 ...

2007年12月5日 · Toshimitsu Takahashi

MeCab + Senna + Tritonn で MySQL 全文検索を試す

以前、自作 N-gram の php プログラムを書いて、日本語全文検索を MySQL の標準機能で試したが、文をまるごと突っ込んで検索するといった場合、AND検索が著しく行われるため、速度が落ちることがわかった。メジャーな組み込み型全文検索を試してみる。 を参考にした。 ダウンロードしてきたパッケージ mecab-0.96.tar.gz mecab-ipadic-2.7.0-20070801.tar.gz senna-1.0.9.tar.gz MySQL-5.0.45-tritonn-1.0.6.tar.gz MeCab のビルドとインストール $ ./configure –prefix=/usr –with-charset=utf8 $ make $ sudo make install Mecab-ipadic のインストール $ ./configure –prefix=/usr –with-charset=utf8 $ make $ sudo make install Senna のビルドとインストール $ ./configure –prefix=/usr $ make $ sudo make install Tritonn (MySQL) のビルドとインストール $ ./configure –prefix=/usr/local/mysql-5.0.45 –localstatedir=/usr/local/mysql-5.0.45/data –libexecdir=/usr/local/mysql-5.0.45/bin –enable-thread-safe-client –enable-local-infile –enable-assembler –with-pic –with-fast-mutexes –with-zlib-dir=bundled –with-big-tables –with-yassl –with-readline –with-archive-storage-engine –with-blackhole-storage-engine –with-example-storage-engine –with-federated-storage-engine –with-innodb –with-charset=utf8 –with-extra-charsets=all –with-mysqld-user=mysql –with-senna –with-mecab $ make $ make bin-dist ...

2007年9月29日 · Toshimitsu Takahashi

PHPでMySQLの標準機能で日本語を全文検索する(4)

検索部分の実装。markupで全文のうち最初にマッチする単語が出てくる部分を抜き出してハイライト化する。 ページ処理はしていない。検索時間は JavaScript で後から表示。 phpにあまり慣れていなかったものの、LAMP を改めて実感する手軽さだった。 find.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 <?php mb\_internal\_encoding("UTF-8"); mb\_regex\_encoding("UTF-8"); header('Content-Type:text/html;charset=utf-8'); require("db.php"); ?> <html> <head> <title>Full Text Search Result</title> <style type="text/css"> h1 { font-weight:normal; color:#2530e5; font-size:200%; font-family:'Arial'; margin-top:20px; } ol,li,p { margin:0; padding:0; } li { list-style:none; margin:1.75em 0; } a { font-weight:bold; } p { margin-top:0.25em; font-size:80%; line-height:1.5; width:530px; } em { font-weight:bold; font-style:normal; background-color:#ff0; } #hitcount { font-size:80%; border-top:#3366cc 1px solid; background-color:#e5ecf9; padding:3px; text-align:right; } </style> </head> <body> <h1>全文検索</h1> <form method="get" action="find.php"> <input type="text" name="find" value="<?php echo($_GET\['find'\]) ?>" style="width:300px"/> <input type="submit" value=" 検索 "/><br/> <input type="checkbox" id="titleonly" name="titleonly" value="1"/><label for="titleonly">タイトルのみ</label> </form> <?php function markup($content, $words) { $disp = ""; $ctnstart = mb_strpos($content, "\\n") + 1; $ret = $ctnstart; foreach ($words as $word){ $ret = mb_stripos($content, $word, $ret); if ($ret === false) { continue; } elseif ($ret < 30) { $ret = 0; } else { $disp = "..."; $ret -= 30; } if (mb_strlen($content) - $ctnstart <= 130) { $disp = mb_substr($content, $ctnstart); break; } $disp .= mb_substr($content, $ret, 130); if (mb_strlen($disp) >= 133) { $disp .= "..."; } break; } if (strlen($disp) == 0) { if (mb_strlen($content) - $ctnstart > 130) { return mb_substr($content, $ctnstart, 130)."..."; } else { return mb_substr($content, $ctnstart); } } $kk = array(); $kk\[\] = "#ffff00"; $kk\[\] = "#00ffff"; $kk\[\] = "#ff00ff"; $kk\[\] = "#00ff00"; $k = 0; foreach ($words as $word){ if (mb_eregi($word, $content, $wdarray)) { foreach ($wdarray as $soeji => $wd){ $disp = mbereg_replace($wd, "<em style=\\"background-color:".$kk\[$k\]."\\">".$wd."</em>", $disp); } } if (++$k == 4) { $k = 0; } } return $disp; } if ($_GET\['find'\]) { $starttime = (float)microtime(); ?> <div id="hitcount"></div> <ol> <?php $dbm = new DBManager("livedocs_ft"); if ($_GET\['titleonly'\] == 1) { $stmt = $dbm->findTitle($_GET\['find'\]); } else { $stmt = $dbm->find($_GET\['find'\]); } $hitcount = 0; if ($stmt->execute()) { while ($record = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "<li><a href=\\"".$record\['uri'\]."\\">".$record\['title'\]."</a>\\n"; if ($_GET\['titleonly'\] == 1) { } else { echo "<p>"; echo markup($record\['content'\], $dbm->getMarkupWords()); echo "</p>"; } echo "<p>"; echo $record\['score'\]; echo "</p></li>"; $hitcount++; } } $endtime = (float)microtime(); ?> </ol> <?php } ?> <script type="text/javascript"><!-- document.getElementById('hitcount').innerHTML = '<?php echo "<b>".$_GET\['find'\]."</b> で検索した結果 <b>".$hitcount."</b> 件 (<b>"; printf("%.3f", ($endtime - $starttime)); echo "</b> 秒)"; ?>'; //--!> </script> </body> </html>

2007年4月29日 · Toshimitsu Takahashi

PHPでMySQLの標準機能で日本語を全文検索する(3)

htmlfiles は HTMLファイルのパスが書かれたテキストリストをコマンドラインでから流し込む。 $ php into.php < htmlfiles into.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <?php mb\_internal\_encoding("UTF-8"); mb\_regex\_encoding("UTF-8"); require_once("db.php"); require_once("htmlindex.php"); class Register { var $dbm; var $uri; var $title; var $content; var $hie; public function Register() { $this->dbm = new DBManager("livedocs_ft"); $this->hie =new HtmlIndexExtractor(); } public function regist($htmlfile) { if (!$this->readFile($htmlfile)) { echo "\[ERR\] Can't open file. : $file\\n"; return; } $this->hie->extract($this->htmltext); if ($this->dbm->insertFullTextIndexPrimary($htmlfile, $this->hie->getTitle(), $this->hie->getContent())) { echo "\[OK\] Inserted into file : $htmlfile.\\n"; } else { echo "\[NG\] Inserted into file : $htmlfile.\\n"; } } private function readFile($file) { $fh = fopen($file, 'r'); if ($fh == FALSE) { return false; } $ctn = ""; while (! feof($fh)) { $ctn .= fgets($fh); } fclose($fh); $this->htmltext = $ctn; return true; } } $rg = new Register(); $stdin = fopen('php://stdin', 'r'); if ($stdin == FALSE) { echo "No STDIN\\n"; exit; } while (!feof($stdin)) { $idxfile = rtrim(fgets($stdin), "\\n"); $idxfile = trim($idxfile); if (strlen($idxfile) > 0) $rg->regist($idxfile); } fclose($stdin); echo "Registing Completed.\\n"; ?>

2007年4月28日 · Toshimitsu Takahashi

PHPでMySQLの標準機能で日本語を全文検索する(2)

PHPからMySQLへの接続にはPDOを使うことにした。テーブルは、単純にURI, タイトルとコンテントをフィールドとして用意、全文用のフィールドを分けたのは、ngram_prim の内容は ngram_sub にも入り重みが増すようにしてみた(一応、効いてると思われる)。Boolean Mode を使うとスコアは利用できないのでその対策は後述。 テーブル ft 1 2 3 4 5 6 7 8 9 10 11 CREATE TABLE ft ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, uri VARCHAR(255) NULL, title VARCHAR(512) NULL, content MEDIUMTEXT NULL, ngram_prim MEDIUMTEXT NULL, ngram_sub MEDIUMTEXT NULL, PRIMARY KEY(id), FULLTEXT INDEX ft_ftindex(ngram_prim, ngram_sub), INDEX ft_uri_index(uri) ); MySQL接続の設定を別ファイルに切り出す。 ...

2007年4月27日 · Toshimitsu Takahashi

MySQLの標準機能で日本語を全文検索する(1)

MySQL には全文検索機能が付いている。だが、ラテン語のようにスペースがないと語句の区切りを認識しないため、そのままでは日本語が検索できない。 MySQLで全文検索 - FULLTEXTインデックスの基礎知識|blog|たたみラボ を参考に構築してみた。 データベースの文字コードは UTF-8 で、最低検索語の指定は1が本当はよいとは思うが少しでも節約したいので、2とした。 my.cnf [mysqld] ft_min_word_len=2 まず必要なのは、日本語の語句分解なのだが、形態素解析ではなく N-gram により分解する。但し、日本語(ひらがな、カタカナ、漢字)、英語(アルファベット、数字)への分解をまずすることで無駄なインデックス作成を抑制するようにしてみた。日本語に関しては N-gram を用いて、英語に関しては、キャメル記法に対しては、分解するようにした。 myindex.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 <?php mb\_internal\_encoding("UTF-8"); mb\_regex\_encoding("UTF-8"); class FullTextSearcher { var $markwords; var $scorequery; public function FullTextSearcher() { } public function search_sql($statement) { return "'". $this->to_ngram($statement, 2) ."' IN BOOLEAN MODE"; } public function getScore() { return "'".$this->scorequery."'"; } public function getMarkupWords() { return $this->markwords; } private function to_ngram($string, $n){ $string = mb\_ereg\_replace("^(\\s| )+","", $string); $string = mb\_ereg\_replace("(\\s| )+$","", $string); $str_array = preg_split("/(\\s| )+/", $string); $result = array(); $markwords = array(); $scores = array(); foreach ($str_array as $str){ if ('-' != substr($str, 0, 1)) { $markwords\[\] = $str; } $r = $this->to\_ngram\_query($str, $n); $result\[\] = $r\[0\]; $scores\[\] = $r\[1\]; } $this->markwords = $markwords; $this->scorequery = join(' ', $scores); return join(' ', $result); } private function to\_ngram\_query($string, $n){ $string = trim($string); if ($string == ''){ return ''; } if ('-' != substr($string, 0, 1)) { $plus = true; } else { $plus = false; $string = substr($string, 1); } $length = mb_strlen($string); if ($length < $n){ if ($plus) { return array("+".$string."*", $string); } else { return array("-".$string."*", ""); } } $ngrams = array(); $scores = array(); $wa = new WordsAnalyzer(); $wa->loadStr($string); $wds = $wa->get_indexes(); foreach ($wds as $ngram){ if ($plus) { $ngrams\[\] = "+" . $ngram; $scores\[\] = $ngram; } else { $ngrams\[\] = "-" . $ngram; } } return array(join(' ', $ngrams), join(' ', $scores)); } } class WordsAnalyzer { private $words; public function WordsAnalyzer() { } public function get_indexes() { return array_keys($this->words); } public function get_fulltext() { return join(' ', array_keys($this->words)); } public function loadStr($str) { $this->words = array(); ereg_replace(13, "", $str); ereg_replace(10, " ", $str); $this->analyze_token($this->split_token($str)); } private function split_token($str) { $token = array(); while (1) { $bytes = mb_ereg("\[一-龠\]+|\[ぁ-ん\]+|\[ァ-ヴー\]+|\[a-zA-Z0-9\]+|\[a-zA-Z0-9\]+", $str, $match); if ($bytes == FALSE) break; $match = $match\[0\]; array_push($token, $match); $pos = strpos($str, $match); $str = substr($str, $pos+$bytes); } return $token; } private function analyze_token($token) { for ($i = 0, $len = count($token); $i < $len; $i++) { $word = $token\[$i\]; if (mb_ereg("\[一-龠\]", $word, $match) != FALSE) { if (mb_strlen($word) > 1) { $this->japanese($word); } else { $this->addword($word); } } else if (mb_ereg("\[ぁ-ん\]", $word, $match) != FALSE) { if (mb_strlen($word) > 1) { $this->hiragana($word); } } else if (mb_ereg("\[ァ-ヴー\]", $word, $match) != FALSE) { if (mb_strlen($word) > 1) { $this->japanese($word); } } else if (mb_ereg("\[a-zA-Z0-9\]", $word, $match) != FALSE) { if (strlen($word) > 0) { // camel-gram $this->english($word); } } else if (mb_ereg("\[a-zA-Z0-9\]", $word, $match) != FALSE) { if (mb_strlen($word) > 0) { // camel-gram $word = mb\_convert\_kana($word, 'rn'); $this->english($word); } } else { $this->addword($word); } } } private function addword($word) { if (strlen($word) == 0) return; $this->words{$word} = true; } private function japanese($str) { // bi-gram $ret = $this->split_ngram($str, 2); foreach ($ret as $key => $value) { if (mb_strlen($value) > 1) { $this->addword($value); } } } private function hiragana($str) { // bi-gram $ret = $this->split_ngram($str, 2); foreach ($ret as $key => $value) { if (mb_strlen($value) > 1) { if (mb_ereg("っ.|を|です|ます|する|ある|いる|から", $value, $match) != FALSE) { } else { $this->addword($value); } } } } private function english($str) { $this->addword($str); // そのままも登録 // キャメル記法を分解して登録 while(1){ $r = ereg("(\[a-z\]|\[A-z\]|\[0-9\])\[a-z\]+", $str, $match); if ($r == FALSE) { break; } $match = $match\[0\]; $this->addword($match); $pos = strpos($str, $match); $str = substr($str, $pos + $r); } } private function split_ngram($string, $n){ $ngrams = array(); $string = trim($string); if ($string == '') return ''; for ($i = 0, $len = mb_strlen($string); $i < $len; $i++) { $ngrams\[\] = mb_substr($string, $i, $n); } return $ngrams; } } ?>

2007年4月25日 · Toshimitsu Takahashi

MySQL - GRANT ステートメント

管理ユーザの追加。管理ユーザ myadmin を追加している。IDENTIFIED BY の後がパスワードとなる。なお、"%" にはlocalhost が含まれないため必要となる。 # ./mysql -u root mysql> GRANT ALL PRIVILEGES ON *.* TO myadmin@localhost IDENTIFIED BY 'myadmin' WITH GRANT OPTION; mysql> GRANT ALL PRIVILEGES ON *.* TO myadmin@"%" IDENTIFIED BY 'myadmin' WITH GRANT OPTION;

2007年4月5日 · Toshimitsu Takahashi

MySQL SQLシェル

まず、シェルを起動。-p でパスワード入力をする。 $ mysql -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 463 to server version: 5.0.20a-log Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer. データベースを列挙する mysql> show databases; +——————–+ | Database | +——————–+ | mt | | mysql | +——————–+ 8 rows in set (0.00 sec) データベースを選択する mysql> use mt; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed ...

2007年3月19日 · Toshimitsu Takahashi