gpt4 book ai didi

php - 弹性索引和php curl的批量索引

转载 作者:行者123 更新时间:2023-12-02 23:28:23 25 4
gpt4 key购买 nike

我正在尝试向ElasticSearch执行php CURL请求以一次索引多个条目(使用_bulk),但是我总是会根据请求正文得到不同的错误

>         $posted = '';
> for ($i = 0; $i < 10; $i++) {
> $posted .= json_encode(array(
> 'index' => new stdClass(),
> )) .'\n';
>
> $posted .= json_encode(array(
> 'id' => $i,
> 'name' => 'XX' . $i,
> ));
>
> if($i < 9){
> $posted .'\n';
> }
> }
>
> $fullURL = 'http://127.0.0.1:9200/myindex/mytype/_bulk';
> $conn = curl_init($fullURL);
>
> curl_setopt($conn, CURLOPT_RETURNTRANSFER, true);
> curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, false);
> curl_setopt($conn, CURLOPT_SSL_VERIFYHOST, false);
> curl_setopt($conn, CURLOPT_FAILONERROR, false);
> curl_setopt($conn, CURLOPT_CUSTOMREQUEST, 'POST');
> curl_setopt($conn, CURLOPT_POSTFIELDS, $posted);
> $res = curl_exec($conn);
> echo $res;

与上面的参数字符串我得到这个错误:

"error":{"root_cause":[{"type":"action_request_validation_exception","reason":"Validation Failed: 1: no requests added;"}],"type":"action_request_validation_exception","reason":"Validation Failed: 1: no requests added;"},"status":400}



我已经用JSON编码的单个请求测试了它,并且工作正常。
那么,如何使用php curl执行_bulk索引?

编辑: ---为了提高可读性而编辑,请参见下面的答案。我尝试了2天在网上找到的所有内容,希望对其他人有所帮助。

最佳答案

我终于明白了!!!

>         $b = array();
> $sets = array();
>
> $params = array(
> '_id' => null,
> '_index' => 'myindex',
> '_type' => 'mytype'
> );
>
> for ($i = 0; $i < 10; $i++) {
> $doc = array(
> 'id' => $i,
> 'name' => 'name ' . $i,
> );
> $set = array(
> array('index' => $params),
> $doc
> );
> $sets[] = $set;
> }
>
> foreach ($sets as $set) {
> foreach ($set as $s) {
> $b[] = json_encode($s);
> }
> }
> $body = join("\n", $b) . "\n";
>
> $conn = curl_init();
> $requestURL = 'http://127.0.0.1:9200/myindex/mytype/_bulk';
> curl_setopt($conn, CURLOPT_URL, $requestURL);
> curl_setopt($conn, CURLOPT_TIMEOUT, 5);
> curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, FALSE);
> curl_setopt($conn, CURLOPT_SSL_VERIFYHOST, FALSE);
> curl_setopt($conn, CURLOPT_RETURNTRANSFER, TRUE);
> curl_setopt($conn, CURLOPT_FAILONERROR, FALSE);
> curl_setopt($conn, CURLOPT_CUSTOMREQUEST, strtoupper('POST'));
> curl_setopt($conn, CURLOPT_FORBID_REUSE, 0);
>
> if (is_array($body) && count($body) > 0) {
> curl_setopt($conn, CURLOPT_POSTFIELDS, json_encode($body));
> } else {
> curl_setopt($conn, CURLOPT_POSTFIELDS, $body);
> }
>
> $response = curl_exec($conn);
> echo $response;

关于php - 弹性索引和php curl的批量索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39933817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com