网站首页 文章专栏 elasticsearch学习(二)----数据批量导入

elasticsearch学习(二)----数据批量导入

编辑时间:2019-06-06 16:51:11 作者:苹果 浏览量:2121




elasticsearch插入数据的格式为:一条索引跟一条数据  {"index":{"_index":"索引名(唯一的)","_type":"类型"}} {数据内容} 

简单的理解就是,_index 就是数据库  _type就是数据表

POST 192.168.1.1:9200/bydls/autoData/_bulk?pretty

{"index":{"_index":"bydls","_type":"autoData"}}
{"id ":1,"title":"这是标题一","cover":"images/home/logo/PHP.jpg","addtime":"2016-05-17 08:03:00"}
{"index":{"_index":"bydls","_type":"autoData"}}
{"id ":2,"title":"这是标题二","cover":"images/home/logo/PHP.jpg","addtime":"2016-05-17 08:03:00"}
{"index":{"_index":"bydls","_type":"autoData"}}
{"id ":3,"title":"这是标题三","cover":"images/home/logo/PHP.jpg","addtime":"2016-05-17 08:03:00"}



结合PHP实现


public function test($indexname = 'test')
{
    $mtime = explode(' ', microtime());
    $startTime = $mtime[1] + $mtime[0];
    $list ='数据库中查出的信息';
    $jsonstr = '';
    foreach ($list as $key => &$value) {
        $attr = array('index' => array('_id' => $value['id']));
        $jsonstr .= json_encode($attr, JSON_UNESCAPED_UNICODE) . "\n" . json_encode($value, JSON_UNESCAPED_UNICODE) . "\n";//拼接成想要的数据格式
    }
    $mtime = explode(' ', microtime());
    $endTime = $mtime[1] + $mtime[0];
    echo "耗时:" . ($endTime - $startTime) . "\n";
    $return = elsearchPost("{$indexname}/bylds/autoData/_bulk?pretty", $jsonstr);
    $mtime = explode(' ', microtime());
    $endTime = $mtime[1] + $mtime[0];
    echo "耗时:" . ($endTime - $startTime) . "\n";
}

function elsearchPost($url, $data, $method = 'post') {
    if (pingAddress('192.168.1.1')) {
        $url1 = 'http://192.168.1.1:9200/';
    } elseif (pingAddress('192.168.1.3')) {
        $url1 = 'http://192.168.1.3:9200/';
    }  else {
        return false;
    }
    $url = $url1 . $url;

    $method = strtolower($method);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json"));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    } elseif ($method == 'put' || $method == 'delete') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $return = curl_exec($ch);
    curl_close($ch);
    return $return;
}

    出自:何冰华个人网站

    地址:https://www.hebinghua.com/

    转载请注明出处


来说两句吧
最新评论