加载中

索引文档

当您向 Elasticsearch 添加文档时,您索引的是 JSON 文档。这自然地映射到 PHP 关联数组,因为它们可以轻松地编码为 JSON。因此,在 Elasticsearch-PHP 中,您创建关联数组并将其传递给客户端进行索引。这里我们介绍了几种将数据摄取到 Elasticsearch 的方法。

在索引文档时,您可以提供 ID,也可以让 Elasticsearch 为您生成一个 ID。


$params = [
    'index' => 'my_index',
    'id'    => 'my_id',
    'body'  => [ 'testField' => 'abc']
];

// Document will be indexed to my_index/_doc/my_id
$response = $client->index($params);
		


$params = [
    'index' => 'my_index',
    'body'  => [ 'testField' => 'abc']
];

// Document will be indexed to my_index/_doc/<autogenerated ID>
$response = $client->index($params);
		


如果您需要设置其他参数,例如 routing 值,您可以在数组中与 index 等参数一起指定。例如,让我们设置这个新文档的路由和时间戳

$params = [
    'index'     => 'my_index',
    'id'        => 'my_id',
    'routing'   => 'company_xyz',
    'timestamp' => strtotime("-1d"),
    'body'      => [ 'testField' => 'abc']
];


$response = $client->index($params);
		


Elasticsearch 还支持文档的批量索引(Bulk Indexing)。Bulk API 需要 JSON 动作/元数据对,并以换行符分隔。在 PHP 中构建文档时,过程也是类似的。您首先创建一个动作数组对象(例如 index 对象),然后创建一个文档主体(body)对象。对所有文档重复此过程。

一个简单的示例如下所示

for($i = 0; $i < 100; $i++) {
    $params['body'][] = [
        'index' => [
            '_index' => 'my_index',
	    ]
    ];

    $params['body'][] = [
        'my_field'     => 'my_value',
        'second_field' => 'some more values'
    ];
}

$responses = $client->bulk($params);
		

在实践中,您拥有的文档数量可能超过了单次批量请求所能发送的数量。在这种情况下,您需要将请求分批并定期发送

$params = ['body' => []];

for ($i = 1; $i <= 1234567; $i++) {
    $params['body'][] = [
        'index' => [
            '_index' => 'my_index',
            '_id'    => $i
        ]
    ];

    $params['body'][] = [
        'my_field'     => 'my_value',
        'second_field' => 'some more values'
    ];

    // Every 1000 documents stop and send the bulk request
    if ($i % 1000 == 0) {
        $responses = $client->bulk($params);

        // erase the old bulk request
        $params = ['body' => []];

        // unset the bulk response when you are done to save memory
        unset($responses);
    }
}

// Send the last batch if it exists
if (!empty($params['body'])) {
    $responses = $client->bulk($params);
}
		
© . This website operates independently and is not affiliated with or endorsed by Elasticsearch B.V. All brand names, logos, and trademarks are the property of their respective owners.