文档章节

官方client php api接口日记

沉淀岁月
 沉淀岁月
发布于 2016/09/08 08:24
字数 1325
阅读 34
收藏 0

​安装:

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

indices()

Index-centric stats and info

nodes()

Node-centric stats and info

cluster()

Cluster-centric stats and info

snapshot()

Methods to snapshot/restore your cluster and indices

cat()

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@localhost:9200',       // HTTP Basic Authentication    'http://user2:pass2@other-host.com:9200' // Different credentials on different host];$client = ClientBuilder::create()                    ->setHosts($hosts)                    ->build();

© 著作权归作者所有

沉淀岁月
粉丝 27
博文 257
码字总数 91615
作品 0
朝阳
高级程序员
私信 提问
PHP 5.3.0以上推荐使用mysqlnd驱动

1.什么是mysqlnd驱动? PHP手册上的描述: MySQL Native Driver is a replacement for the MySQL Client Library (libmysql). MySQL Native Driver is part of the official PHP sources as of......

月影又无痕
2013/06/27
474
1
aws emr api 接口开发 curl 60 ,77错误代码

curl 出现错误代码60 ,77 开发日记:aws emr api 接口开发 Today I was trying to consume an external video API for streaming a set of videos; so I got the code for the PHP source, c......

成越
2016/11/10
96
0
flc1125/alidayu

阿里大于(鱼) - v2.0 PS:阿里短信 https://github.com/flc1125/dysms 更新 v2.0.6 (2017-08-12) fixed #6 v2.0.5 (2017-01-25) 修复autoload.php https://github.com/flc1125/alidayu/issue......

flc1125
2017/03/10
0
0
EosTool - PHP版的EOS区块链应用开发包

EosTool的目的是消除使用PHP开发EOS区块链应用的痛苦,例如: 通过Nodeos和Keosd的RPC接口调用其功能 离线生成EOS格式的私钥和公钥 使用本地私钥生成符合EOS要求的交易签名 将交易对象序列化...

汇智网教程
2018/12/06
33
0
SLF4J 教程

一、介绍: 简单日记门面(simple logging Facade for java)SLF4J是为各种loging APIs提供一个简单统一的接口,从而使得最终用户能够在部署的时候配置自己希望的loging APIs实现。 Logging AP...

红薯
2008/12/09
3.1K
1

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周三乱弹 —— 调查人员问狗 那你在做什么啊?

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 小小编辑推荐:《Let It Be》- John Denver 《Let It Be》- John Denver 手机党少年们想听歌,请使劲儿戳(这里) @FalconChen :每天看一遍,...

小小编辑
今天
6
0
高效程序员的45个习惯总结版-文末脑图

1 做事 一个重大的错误应该被当做一次学习而不是指责他人的机会,团队成员一起工作,应该互相帮助,而不是互相指责 2 欲速则不达 不要为了修复问题而去修复,要投入时间和精力保持代码整洁 ...

阿提说说
今天
18
0
带南海九段线分位数地图可视化(R语言版)

今天带来一篇承诺虾神的可视化博客。内容是使用R语言进行带南海九段线分位数地图可视化。虾神的原博文地址如下(Python版)。 Python实现带南海九段线分位数地图完整可视化版本(附代码及数据...

胖胖雕
今天
12
0
Nginx 的进程结构,你明白吗?

Nginx 进程结构 这篇文章我们来看下 Nginx 的进程结构,Nginx 其实有两种进程结构: 单进程结构 多进程结构 单进程结构实际上不适用于生产环境,只适合我们做开发调试使用。因为在生产环境中...

武培轩
今天
20
0
蓝鲸平台部署

环境 系统:Centos7 依赖包:java8 主机: 10.0.1.150 域名:paas.ops.net;cmdb.ops.net;job.ops.net 生成SSH key ssh-keygen -t rsa -P '' 生成证书 https://bk.tencent.com/download_ssl/......

以谁为师
今天
7
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部