Elasticsearch-PHP 索引操作2
阿新 • • 發佈:2017-10-12
values sea start lang for 轉換 key filter 支持
索引操作
索引在客戶端非常容易。因為關聯數組很容易轉換為JSON文檔,索引文檔只是提供正確和結構性的關聯數組和調用方法。
單文檔索引
當你索引你個文檔時,可以自己提供一個ID,也可以讓elasticsearch 為你生成一個ID。
提供一個ID值
- $params = array();
- $params[‘body‘] = array(‘testField‘ => ‘abc‘);
- $params[‘index‘] = ‘my_index‘;
- $params[‘type‘] = ‘my_type‘;
- $params[‘id‘] = ‘my_id‘;
- // Document will be indexed to my_index/my_type/my_id
- $ret = $client->index($params);
缺省ID值
- $params = array();
- $params[‘body‘] = array(‘testField‘ => ‘abc‘);
- $params[‘index‘] = ‘my_index‘;
- $params[‘type‘] = ‘my_type‘;
- // Document will be indexed to my_index/my_type/<autogenerated_id>
- $ret = $client->index($params);
像大多數其他API一樣,還有一些其他參數可以指定。它們在參數數組中指定的就像是索引或類型。例如,讓我們設置這個新文檔的路由和時間戳。
附加參數
- $params = array();
- $params[‘body‘] = array(‘testField‘ => ‘xyz‘);
- $params[‘index‘] = ‘my_index‘;
- $params[‘type‘] = ‘my_type‘;
- $params[‘routing‘] = ‘company_xyz‘;
- $params[‘timestamp‘] = strtotime("-1d");
- $ret = $client->index($params);
批量索引
Elasticsearch還支持批量索引文檔。客戶端也提供一個批量索引的接口,但是並不是很友好的。在未來我們會添加“幫助”方法去簡化這個流程。
批量的API方法期待一個批量的body和友好的elasticsearch所期待的是一樣的:JSON的 動作/元數據對被新行分割。一個常見的批量操作如下:
使用PHP數組批量索引
- for($i = 0; $i < 100; $i++) {
- $params[‘body‘][] = array(
- ‘index‘ => array(
- ‘_id‘ => $i
- )
- );
- $params[‘body‘][] = array(
- ‘my_field‘ => ‘my_value‘,
- ‘second_field‘ => ‘some more values‘
- );
- }
- $responses = $client->bulk($params);
你當然可以使用任何一個批量方法,這裏有一個使用upserts的例子:
使用PHP數組進行批量upserting操縱
- for($i = 0; $i < 100; $i++) {
- $params[‘body‘][] = array(
- ‘update‘ => array(
- ‘_id‘ => $i
- )
- );
- $params[‘body‘][] = array(
- ‘doc_as_upsert‘ => ‘true‘,
- ‘doc‘ => array(
- ‘my_field‘ => ‘my_value‘,
- ‘second_field‘ => ‘some more values‘
- )
- );
- }
- $responses = $client->bulk($params);
批量更新與Nowdocs
如果你是手工的指定塊或者是從現有的JSON文件中提取它們,Nowdocs 可能是最好的方法。否則,當你通過算法去構造它們,小心確保使用 ‘\n"換行符分割每一行,包括最後一行。
批量索引
- $params = array();
- $params[‘body‘] = <<<‘EOT‘
- { "index" : { "_index" : "my_index", "_type" : "my_type", "_id" : "1" } }
- { "field1" : "value1" }
- EOT;
- $ret = $client->bulk($params);
像批量API一樣,如果你在參數中制定索引/類型,你可以從批量請求本身省略掉它(這往往可以省略大量的空間和冗余的數據傳輸)
批量索引 w/ 明確的索引/類型
- $params = array();
- $params[‘body‘] = <<<‘EOT‘
- { "index" : { "_id" : "1" } }
- { "field1" : "value1" }
- EOT;
- $params[‘index‘] = ‘my_index‘;
- $params[‘type‘] = ‘my_type‘;
- $ret = $client->bulk($params);
Elasticsearch-PHP 索引操作2