【elasticsearch】批量更新数据

软件版本:

  • php 5.6.31
  • elasticsearch 6.1.1
  • Yii 2 框架

elasticsearch 扩展:

{
    "require": {
        "elasticsearch/elasticsearch": "~5.0"
    }
}

代码:

function actionArticle()
{
    $open_sites = Yii::$app->getDb()->createCommand(
        "select indicator from {{%site}} where status = 1 order by id asc"
    )->queryAll();
    if (empty($open_sites)) {
        return 0;
    }

    foreach ($open_sites as $open_site) {
        $indicator = $open_site['indicator'];
        $articles = Yii::$app->getDb()->createCommand(
            "select id, heat from {{%article_{$indicator}}} order by id asc"
        )->queryAll();
        if (empty($articles)) {
            continue;
        }

        $es_params = ['index' => $indicator, 'type' => 'doc'];
        $body = [];
        foreach ($articles as $article) {
            $article_id = $article['id'];
            $body[] = ['update' => ['_id' => "article_{$article_id}"]];
            $body[] = ['doc' => ['heat' => $article['heat']]];

            if (count($body) >= 2000) {
                $es_params['body'] = $body;
                // file_put_contents('es_bulk.log', print_r($es_params, true));die;
                Yii::$app->elasticsearch->client->bulk($es_params);

                $body = [];
            }
        }

        if (!empty($body)) {
            $es_params['body'] = $body;
            Yii::$app->elasticsearch->client->bulk($es_params);
        }
    }

    return 0;
}

对应 elasticsearch 批量更新 api 的参数请求结构:

Array
(
    [index] => cn
    [type] => doc
    [body] => Array
        (
            [0] => Array
                (
                    [update] => Array
                        (
                            [_id] => article_1
                        )

                )

            [1] => Array
                (
                    [doc] => Array
                        (
                            [heat] => 0.00
                        )

                )

            [2] => Array
                (
                    [update] => Array
                        (
                            [_id] => article_2
                        )

                )

            [3] => Array
                (
                    [doc] => Array
                        (
                            [heat] => 0.00
                        )

                )

            ...

        )

)

你可能感兴趣的:(PHP,elasticsearch)