1. 程式人生 > >Elasticsearch-PHP 索引操作2

Elasticsearch-PHP 索引操作2

values sea start lang for 轉換 key filter 支持

索引操作

索引在客戶端非常容易。因為關聯數組很容易轉換為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);

Elasticsearch-PHP 索引操作2