安装:
composer.json
{ "require": { "elasticsearch/elasticsearch": "~2.0@beta" }}
curl -s http://getcomposer.org/installer | phpphp composer.phar install --no-dev
require 'vendor/autoload.php';$client = Elasticsearch\ClientBuilder::create()->build();
主机配置:
$hosts = [ '192.168.1.1:9200', // IP + Port '192.168.1.2', // Just IP 'mydomain.server.com:9201', // Domain + Port 'mydomain2.server.com', // Just Domain 'https://localhost', // SSL to localhost 'https://192.168.1.3:9200' // SSL to IP + Port];$client = ClientBuilder::create() // Instantiate a new ClientBuilder ->setHosts($hosts) // Set the hosts ->build(); // Build the client object
创建一个索引
$client = ClientBuilder::create()->build();
$params = [ 'index' => 'my_index'];// Create the index
$response = $client->indices()->create($params);
//创建带有字段映射的索引
$client = ClientBuilder::create()->build();$params = [ 'index' => 'my_index', 'body' => [ 'settings' => [ 'number_of_shards' => 3, 'number_of_replicas' => 2 ], 'mappings' => [ 'my_type' => [ '_source' => [ 'enabled' => true ], 'properties' => [ 'first_name' => [ 'type' => 'string', 'analyzer' => 'standard' ], 'age' => [ 'type' => 'integer' ] ] ] ] ]];// Create the index with mappings and settings now$response = $client->indices()->create($params);
//高级创建索引
$params = [ 'index' => 'reuters', 'body' => [ 'settings' => [ 'number_of_shards' => 1, 'number_of_replicas' => 0, 'analysis' => [ 'filter' => [ 'shingle' => [ 'type' => 'shingle' ] ], 'char_filter' => [ 'pre_negs' => [ 'type' => 'pattern_replace', 'pattern' => '(\\w+)\\s+((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\b', 'replacement' => '~$1 $2' ], 'post_negs' => [ 'type' => 'pattern_replace', 'pattern' => '\\b((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\s+(\\w+)', 'replacement' => '$1 ~$2' ] ], 'analyzer' => [ 'reuters' => [ 'type' => 'custom', 'tokenizer' => 'standard', 'filter' => ['lowercase', 'stop', 'kstem'] ] ] ] ], 'mappings' => [ '_default_' => [ 'properties' => [ 'title' => [ 'type' => 'string', 'analyzer' => 'reuters', 'term_vector' => 'yes', 'copy_to' => 'combined' ], 'body' => [ 'type' => 'string', 'analyzer' => 'reuters', 'term_vector' => 'yes', 'copy_to' => 'combined' ], 'combined' => [ 'type' => 'string', 'analyzer' => 'reuters', 'term_vector' => 'yes' ], 'topics' => [ 'type' => 'string', 'index' => 'not_analyzed' ], 'places' => [ 'type' => 'string', 'index' => 'not_analyzed' ] ] ], 'my_type' => [ 'properties' => [ 'my_field' => [ 'type' => 'string' ] ] ] ] ]];$client->indices()->create($params);
删除一个索引
$params = ['index' => 'my_index'];$response = $client->indices()->delete($params);
动态修改索引设置
$params = [ 'index' => 'my_index', 'body' => [ 'settings' => [ 'number_of_replicas' => 0, 'refresh_interval' => -1 ] ]];$response = $client->indices()->putSettings($params);
//获取索引设置
// Get settings for one index$params = ['index' => 'my_index'];$response = $client->indices()->getSettings($params);// Get settings for several indices$params = [ 'index' => [ 'my_index', 'my_index2' ]];$response = $client->indices()->getSettings($params);
//修改或增加已经存在的索引字段映射modify or add to an existing index’s mapping
// Set the index and type$params = [ 'index' => 'my_index', 'type' => 'my_type2', 'body' => [ 'my_type2' => [ '_source' => [ 'enabled' => true ], 'properties' => [ 'first_name' => [ 'type' => 'string', 'analyzer' => 'standard' ], 'age' => [ 'type' => 'integer' ] ] ] ]];// Update the index mapping$client->indices()->putMapping($params);
获取索引字段映射
// Get mappings for all indexes and types$response = $client->indices()->getMapping();// Get mappings for all types in 'my_index'$params = ['index' => 'my_index'];$response = $client->indices()->getMapping($params);// Get mappings for all types of 'my_type', regardless of index$params = ['type' => 'my_type' ];$response = $client->indices()->getMapping($params);// Get mapping 'my_type' in 'my_index'$params = [ 'index' => 'my_index' 'type' => 'my_type'];$response = $client->indices()->getMapping($params);// Get mappings for two indexes$params = [ 'index' => [ 'my_index', 'my_index2' ]];$response = $client->indices()->getMapping($params);
索引文档
单个文档索引,指定ID
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'testField' => 'abc']];// Document will be indexed to my_index/my_type/my_id$response = $client->index($params);
单个文档索引,不指定ID,自动生成
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'body' => [ 'testField' => 'abc']];// Document will be indexed to my_index/my_type/<autogenerated ID>$response = $client->index($params);
附加参数
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'routing' => 'company_xyz', 'timestamp' => strtotime("-1d"), 'body' => [ 'testField' => 'abc']];$response = $client->index($params);
分块建文档
for($i = 0; $i < 100; $i++) { $params['body'][] = [ 'index' => [ '_index' => 'my_index', '_type' => 'my_type', ] ]; $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', '_type' => 'my_type', '_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 existsif (!empty($params['body'])) { $responses = $client->bulk($params);}
获得文档
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id'];// Get doc at /my_index/my_type/my_id$response = $client->get($params);
更新文档
部分文档更新
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'doc' => [ 'new_field' => 'abc' ] ]];// Update doc at /my_index/my_type/my_id$response = $client->update($params);
脚本更新
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'script' => 'ctx._source.counter += count', 'params' => [ 'count' => 4 ] ]];$response = $client->update($params);
更新或插入操作
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'script' => 'ctx._source.counter += count', 'params' => [ 'count' => 4 ], 'upsert' => [ 'counter' => 1 ] ]];$response = $client->update($params);
删除文档
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id' ]; // Delete doc at /my_index/my_type/my_id $response = $client->delete($params);
搜索操作
匹配查询
curl -XGET 'localhost:9200/my_index/my_type/_search' -d '{ "query" : { "match" : { "testField" : "abc" } } }'
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'body' => [ 'query' => [ 'match' => [ 'testField' => 'abc' ] ] ]];$results = $client->search($params);
print_r(json_encode($params['body']));{"query":{"match":{"testField":"abc"}}}
原生JSON查询
$json = '{ "query" : { "match" : { "testField" : "abc" } } }';$params = [ 'index' => 'my_index', 'type' => 'my_type', 'body' => $json];$results = $client->search($params);
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'body' => [ 'query' => [ 'match' => [ 'testField' => 'abc' ] ] ]];$results = $client->search($params);$milliseconds = $results['took'];$maxScore = $results['hits']['max_score'];$score = $results['hits']['hits'][0]['_score'];$doc = $results['hits']['hits'][0]['_source'];
布尔查询
curl -XGET 'localhost:9200/my_index/my_type/_search' -d '{ "query" : { "bool" : { "must": [ { "match" : { "testField" : "abc" } }, { "match" : { "testField2" : "xyz" } } ] } } }'
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'body' => [ 'query' => [ 'bool' => [ 'must' => [ [ 'match' => [ 'testField' => 'abc' ] ], [ 'match' => [ 'testField2' => 'xyz' ] ], ] ] ] ]];$results = $client->search($params);
复杂的查询
curl -XGET 'localhost:9200/my_index/my_type/_search' -d '{ "query" : { "filtered" : { "filter" : { "term" : { "my_field" : "abc" } }, "query" : { "match" : { "my_other_field" : "xyz" } } } } }'
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'body' => [ 'query' => [ 'filtered' => [ 'filter' => [ 'term' => [ 'my_field' => 'abc' ] ], 'query' => [ 'match' => [ 'my_other_field' => 'xyz' ] ] ] ] ]];$results = $client->search($params);
扫描/滚动查询
$client = ClientBuilder::create()->build();$params = [ "search_type" => "scan", // use search_type=scan "scroll" => "30s", // how long between scroll requests. should be small! "size" => 50, // how many results *per shard* you want back "index" => "my_index", "body" => [ "query" => [ "match_all" => [] ] ]];$docs = $client->search($params); // Execute the search$scroll_id = $docs['_scroll_id']; // The response will contain no results, just a _scroll_id// Now we loop until the scroll "cursors" are exhaustedwhile (\true) { // Execute a Scroll request $response = $client->scroll([ "scroll_id" => $scroll_id, //...using our previously obtained _scroll_id "scroll" => "30s" // and the same timeout window ] ); // Check to see if we got any search hits from the scroll if (count($response['hits']['hits']) > 0) { // If yes, Do Work Here // Get new scroll_id // Must always refresh your _scroll_id! It can change sometimes $scroll_id = $response['_scroll_id']; } else { // No results, scroll cursor is empty. You've exported all the data break; }}
Namespace | Functionality |
---|---|
| Index-centric stats and info |
| Node-centric stats and info |
| Cluster-centric stats and info |
| Methods to snapshot/restore your cluster and indices |
| Access to the Cat API (which is generally used standalone from the command line |
$client = ClientBuilder::create()->build();// Index Stats// Corresponds to curl -XGET localhost:9200/_stats$response = $client->indices()->stats();// Node Stats// Corresponds to curl -XGET localhost:9200/_nodes/stats$response = $client->nodes()->stats();// Cluster Stats// Corresponds to curl -XGET localhost:9200/_cluster/stats$response = $client->cluster()->stats();
$client = ClientBuilder::create()->build();// Corresponds to curl -XGET localhost:9200/my_index/_stats$params['index'] = 'my_index';$response = $client->indices()->stats($params);// Corresponds to curl -XGET localhost:9200/my_index1,my_index2/_stats$params['index'] = array('my_index1', 'my_index2');$response = $client->indices()->stats($params);
$params['body'] = array( 'actions' => array( array( 'add' => array( 'index' => 'myindex', 'alias' => 'myalias' ) ) ));$client->indices()->updateAliases($params);
HTTP认证
$hosts = [ 'http://user:pass:9200', // HTTP Basic Authentication 'http://user2:pass2@other-host.com:9200' // Different credentials on different host];$client = ClientBuilder::create() ->setHosts($hosts) ->build();