Elasticsearch-PHP 索引操作2

索引在客户端非常容易。因为关联数组很容易转换为JSON文档,索引文档只是提供正确和结构性的关联数组和调用方法。

单文档索引

当你索引你个文档时,可以自己提供一个ID,也可以让elasticsearch 为你生成一个ID。

提供一个ID值

  1. $params = array();
  2. $params['body'] = array('testField' => 'abc');
  3. $params['index'] = 'my_index';
  4. $params['type'] = 'my_type';
  5. $params['id'] = 'my_id';
  6. // Document will be indexed to my_index/my_type/my_id
  7. $ret = $client->index($params);

缺省ID值

  1. $params = array();
  2. $params['body'] = array('testField' => 'abc');
  3. $params['index'] = 'my_index';
  4. $params['type'] = 'my_type';
  5. // Document will be indexed to my_index/my_type/<autogenerated_id>
  6. $ret = $client->index($params);

像大多数其他API一样,还有一些其他参数可以指定。它们在参数数组中指定的就像是索引或类型。例如,让我们设置这个新文档的路由和时间戳。

附加参数

  1. $params = array();
  2. $params['body'] = array('testField' => 'xyz');
  3. $params['index'] = 'my_index';
  4. $params['type'] = 'my_type';
  5. $params['routing'] = 'company_xyz';
  6. $params['timestamp'] = strtotime("-1d");
  7. $ret = $client->index($params);

批量索引

Elasticsearch还支持批量索引文档。客户端也提供一个批量索引的接口,但是并不是很友好的。在未来我们会添加“帮助”方法去简化这个流程。

批量的API方法期待一个批量的body和友好的elasticsearch所期待的是一样的:JSON的 动作/元数据对被新行分割。一个常见的批量操作如下:

使用PHP数组批量索引

  1. for($i = 0; $i < 100; $i++) {
  2. $params['body'][] = array(
  3. 'index' => array(
  4. '_id' => $i
  5. )
  6. );
  7. $params['body'][] = array(
  8. 'my_field' => 'my_value',
  9. 'second_field' => 'some more values'
  10. );
  11. }
  12. $responses = $client->bulk($params);

你当然可以使用任何一个批量方法,这里有一个使用upserts的例子:

使用PHP数组进行批量upserting操纵

  1. for($i = 0; $i < 100; $i++) {
  2. $params['body'][] = array(
  3. 'update' => array(
  4. '_id' => $i
  5. )
  6. );
  7. $params['body'][] = array(
  8. 'doc_as_upsert' => 'true',
  9. 'doc' => array(
  10. 'my_field' => 'my_value',
  11. 'second_field' => 'some more values'
  12. )
  13. );
  14. }
  15. $responses = $client->bulk($params);

批量更新与Nowdocs

如果你是手工的指定块或者是从现有的JSON文件中提取它们,Nowdocs 可能是最好的方法。否则,当你通过算法去构造它们,小心确保使用 ‘\n"换行符分割每一行,包括最后一行。

批量索引

  1. $params = array();
  2. $params['body'] = <<<'EOT'
  3. { "index" : { "_index" : "my_index", "_type" : "my_type", "_id" : "1" } }
  4. { "field1" : "value1" }
  5. EOT;
  6. $ret = $client->bulk($params);

像批量API一样,如果你在参数中制定索引/类型,你可以从批量请求本身省略掉它(这往往可以省略大量的空间和冗余的数据传输)

批量索引 w/ 明确的索引/类型

    1. $params = array();
    2. $params['body'] = <<<'EOT'
    3. { "index" : { "_id" : "1" } }
    4. { "field1" : "value1" }
    5. EOT;
    6. $params['index'] = 'my_index';
    7. $params['type'] = 'my_type';
    8. $ret = $client->bulk($params);