4.elasticsearch-php中future模式

参考链接

<?php
require 'vendor/autoload.php';
use Monolog\Logger;
use Elasticsearch\ClientBuilder;

$logger = new Logger('name');
$logger->pushHandler(new \Monolog\Handler\StreamHandler('future.log'));
// 更改批量值
// 默认的批量值为 100 个,意味着在客户端强制 future 对象解析前(执行 curl_multi 调用),队列可以容纳 100 个请求。批量值可以更改,取决于你的需求。
// 批量值的调整是通过配置 HTTP handler 时设置 max_handles 参数来实现
$handlerParams = [
    'max_handles' => 500
];
$defaultHandler = ClientBuilder::defaultHandler($handlerParams);
$client = ClientBuilder::create()->setLogger($logger)->setHandler($defaultHandler)->build();


// 使用 Future 模式(异步模式)
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' =>1,
    'client' => [
        'future' => 'lazy'
    ]
];
// 返回一个future对象,future对象是待处理对象,类似占位符
//$future = $client->get($params);
//$doc = $future['_source'];
//print_r($doc);

// 上面的设置会更改批量发送数量为 500。注意:不管队列数量是否为最大批量值,强制解析 future 对象都会引起底层的 curl 执行批量请求操作。
// 在如下的示例中,只有 499 个对象加入队列,但最后的 future 对象被解析会引起强制发送批量请求:
$futures = [];
for ($i = 1; $i <499; $i++){
    $params = [
        'index' => 'my_index',
        'type' => 'my_type',
        'id' => $i,
        'client' => [
            'future' => 'lazy'
        ]
    ];
    $futures[] = $client->get($params);
}
// future 对象可以用迭代关联数组的方式解析特定的值(轮流解析未解析的请求和值)
//foreach ($futures as $future) {
//    print_r($future['_source']);
//}
// 如果你想强制解析 future 对象,但又不立刻获取响应数据。可以用 future 对象的 wait() 方法来强制解析
// print_r($futures[497]->wait());

// 各种批量执行
// 队列里面允许存在各种请求。比如,你可以把 get 请求、index 请求和 search 请求放到队列里面:
$futures = [];
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 1,
    'client' => [
        'future' => 'lazy'
    ]
];
$futures['getRequest'] = $client->get($params);
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 2,
    'body' => [
        'field' => 'name'
    ],
    'client' => [
        'future' => 'lazy'
    ]
];
$futures['indexRequest'] = $client->index($params);
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'body' => [
        'query' => [
            'match' => [
                'field' => 'name'
            ]
        ]
    ],
    'client' => [
        'future' => 'lazy'
    ]
];
$futures['searchRequest'] = $client->search($params);

$doc = $futures['getRequest']['_source'];
print_r($doc);
$searchResults = $futures['searchRequest']['hits'];
print_r($searchResults);
发布了77 篇原创文章 · 获赞 33 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39337886/article/details/103800106
今日推荐