Skip to content

Instantly share code, notes, and snippets.

@horike37
Last active December 10, 2015 15:27
Show Gist options
  • Save horike37/611ab3c05537b2502294 to your computer and use it in GitHub Desktop.
Save horike37/611ab3c05537b2502294 to your computer and use it in GitHub Desktop.
WordPress上の記事をElasticaをつかってElasticSearchにインポート
<?php
require_once 'vendor/autoload.php';
use Elastica\Client;
use Elastica\Query;
use Elastica\Query\QueryString;
add_action( 'pre_get_posts', function($query){
if ( $query->is_search() && $query->is_main_query() ) {
$client = new \Elastica\Client(array(
'host' => '<ESへのエンドポイント>',
'port' => 80
));
$type = $client->getIndex('mysite')->getType('content');
$qs = new QueryString();
$qs->setQuery(get_search_query());
$query_es = Query::create($qs);
$resultSet = $type->search($query_es);
$post_ids = array();
foreach ( $resultSet as $r ) {
$post_ids[] = $r->getID();
}
$query->set('post__in', $post_ids);
$query->set('s', '');
$query->set('post_type', 'post');
}
});
<?php
require_once 'vendor/autoload.php';
use Elastica\Client;
use Elastica\Type\Mapping;
use Elastica\Bulk;
$client = new \Elastica\Client(array(
'host' => '<ESへのエンドポイント>',
'port' => 80
));
$index = $client->getIndex('mysite');
$index->create(array(), true);
$type = $index->getType('content');
$mapping = new Mapping($type,
array(
'title' => array(
'type' => 'string',
'analyzer' => 'kuromoji',
),
'content' => array(
'type' => 'string',
'analyzer' => 'kuromoji',
)
)
);
$type->setMapping($mapping);
$my_posts = get_posts( array('posts_per_page' => -1) );
$docs = array();
foreach ( $my_posts as $p ) {
$d = array(
'title' => (string)$p->post_title,
'content' => (string)strip_tags($p->post_content)
);
$docs[] = $type->createDocument((int)$p->ID, $d);
}
$bulk = new Bulk($client);
$bulk->setType($type);
$bulk->addDocuments($docs);
$res = $bulk->send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment