PHPからElasticsearchを利用するため、「Elastica」というクライントライブラリを使ってIndexを作成してみる。
使い方はテストケースを見よ、ということらしいのテストケースを参考にする。
(Elasticsearchとkuromojiプラグインはインストールしておく)
特に理由は無いが、サンプルデータとしてナタリーのRSSを使う。
RSSは適当なところにファイルとして保存しておく。
XMLを読み込んでBulkでインデックスを一括作成する。
<?php
require_once '../vendor/autoload.php';
use Elastica\Client;
use Elastica\Type\Mapping;
use Elastica\Bulk;
$client = new Client();
$index = $client->getIndex('natalie_data');
$index->create(array(), true);//2引数のboolは同名Indexを削除して再作成するかどうか
// http://elastica.io/api/classes/Elastica.Index.html
$type = $index->getType('comic_news');
// mappingを指定する
$mapping = new Mapping($type,
array(
'title' => array(
'type' => 'string',
'analyzer' => 'kuromoji',
),
'summary' => array(
'type' => 'string',
'analyzer' => 'kuromoji',
),
'author' => array(
'type' => 'object',
'properties' => array(
'name' => array(
'type' => 'string',
),
'author_email' => array(
'type' => 'string',
),
),
),
'link' => array(
'type' => 'string',
'index' => 'not_analyzed',
),
'updated' => array(
'type' => 'date',
),
)
);
$type->setMapping($mapping);
$xml = simplexml_load_file('natalie_comic.xml');
$docs = array();
foreach ($xml->entry as $entry) {
echo (string)$entry->title . "\n";
$d = array(
'title' => (string)$entry->title,
'summary' => (string)$entry->summary,
'author' => array(
'name' => (string)$entry->author->name,
'author_email' => (string)$entry->author->author_email,
),
'link' => (string)$entry->link->attributes()->href,
'updated' => (string)$entry->updated
);
$docs[] = $type->createDocument((int)$entry->id, $d);
}
$bulk = new Bulk($client);
$bulk->setType($type);
$bulk->addDocuments($docs);
$res = $bulk->send();//sendしないとダメ
if ($res->isOk()) {
echo 'done' . "\n";
} else {
echo $res->getError() . "\n";
}