0

我正在尝试通过批量 API 将文档添加到弹性搜索索引。我的 CURL 查询在命令行上运行良好,我将其转换为 PHP。

当我尝试运行 PHP 代码时,什么也没有发生。弹性搜索中没有将文档添加到索引中,也没有出现任何错误。

卷曲查询:

curl -H "Content-Type:application/json" -XPOST "http://localhost:9200/inven/default/_bulk?pretty" --data-binary "@file_name.json"

PHP 查询:

 $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'http://localhost:9200/inven/default/_bulk?pretty');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $post = array(
        'file' => '@' .realpath('file_name.json')
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);

我也设置ini_set('max_execution_time', 0);了,以防万一,它超时了。可能是什么问题?

4

3 回答 3

2

您没有发送实际的文件内容,只是将其文件名作为字符串发送。尝试这个:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:9200/inven/default/_bulk?pretty');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1 );

// The line below assumes the file_name.json is located in the same directory
// with this script, if not change the path to the file with the correct one.
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('file_name.json') );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
于 2019-01-09T17:36:01.733 回答
0

如果您使用的是 PHP 5.5+,请使用:

$post = [
    'file' => curl_file_create('file_name.json')
];

更多信息检查:修复 CURL 文件上传

于 2019-01-09T17:41:27.267 回答
0

尝试$post = '@' .realpath('file_name.json')

于 2019-01-09T15:32:59.833 回答