1. 程式人生 > >php-elasticsearch bulk批量插入數據

php-elasticsearch bulk批量插入數據

hid dex none ram res hosts _id end 生成

1.單條插入

技術分享圖片
<?php
include ‘../vendor/Elasticsearch/autoload.php‘;
$a[‘hosts‘] = array(
#需要用戶名時 http://user:[email protected]:por 其他時候直接寫ip:port
‘ip:9200‘,
);
$client = new \Elasticsearch\Client($a);

#單條插入
$params = array();
$params[‘body‘] = array(
‘xzdfaf‘ => ‘xfsa‘
);
$params[‘index‘] = ‘paopao‘;
$params[‘type‘] = ‘test‘; // $params[‘id‘] = ‘w1231313‘; $ret = $client->index($params);
View Code

2.批量插入

技術分享圖片
<?php
include ‘../vendor/Elasticsearch/autoload.php‘;
$a[‘hosts‘] = array(
#需要用戶名時 http://user:[email protected]:por 其他時候直接寫ip:port
‘ip:9200‘,
);
$client = new \Elasticsearch\Client($a
); #bulk批量生成 $params[‘index‘] = ‘paopao‘; $params[‘type‘] = ‘test‘; for($i = 21; $i <= 30; $i ++) { $params[‘body‘][]=array( ‘create‘ => array( #註意create也可換成index ‘_id‘=>$i ), ); $params[‘body‘][]=array( ‘aa‘=>$i ); } $res = $client->bulk($params);
View Code

3.以上必須指定id,但是我想用默認的id怎麽辦

技術分享圖片
<?php
include ‘../vendor/Elasticsearch/autoload.php‘;
$a[‘hosts‘] = array(
#需要用戶名時 http://user:[email protected]:por 其他時候直接寫ip:port
‘ip:9200‘,
);
$client = new \Elasticsearch\Client($a);
#bulk批量生成
for($i = 41; $i <= 50; $i ++) {
$params[‘body‘][]=array(
‘index‘ => array(
‘_index‘=> ‘paopao‘,
‘_type‘=> ‘test‘
),
);

$params[‘body‘][]=array(
‘aa‘=>$i
);
}
$res = $client->bulk($params);
View Code

4.其他拓展
行為 解釋

create
當文檔不存在時創建
index 
創建新文檔或替換已有文檔。
update
局部更新文檔。
delete
 刪除一個文檔。

POST /_bulk
{ "delete": { "_index": "website", "_type": "blog", "_id": "123" }} 
{ "create": { "_index": "website", "_type": "blog", "_id": "123" }}
{ "title": "My first blog post" }
{ "index": { "_index": "website", "_type": "blog" }}
{ "title": "My second blog post" }
{ "update": { "_index": "website", "_type": "blog", "_id": "123", "_retry_on_conflict" : 3} }
{ "doc" : {"title" : "My updated blog post"} } 


請註意 delete 動作不能有請求體,它後面跟著的是另外一個操作。

謹記最後一個換行符不要落下。

php-elasticsearch bulk批量插入數據