创建client对象
<?php
$logger = new Logger('name');
$logger->pushHandler(new StreamHandler('monolog.log', logger::INFO));
$handlerParams = [
'max_handles' => 100
];
$defaultHandler = ClientBuilder::defaultHandler($handlerParams);
$hosts = [
'127.0.0.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)->setLogger($logger) // Set the hosts
->setHandler($defaultHandler)
->build();//创建client对象
创建索引
$params = [
'index' => 'mysql_table_test',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'properties' => [
'first_name' => [
'type' => 'text',
'analyzer' => 'standard'
],
'age' => [
'type' => 'integer'
]
]
]
]
];
$response = $client->indices()->create($params);
新增索引字段
$params = [
'index' => 'mysql_table_test',
'body' => [
'properties' => [
'first_name' => [
'type' => 'text',
'analyzer' => 'standard'
],
'age' => [
'type' => 'integer'
]
]
]
];
$response = $client->indices()->putMapping($params);
修改索引设置信息
$params = [
'index' => 'mysql_table_test',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 1
],
]
];
$client->indices()->putSettings($params);
新增文档
$params = [
'index' => 'mysql_table_test',
'type' => 'out',
//'id' => 10,//指定id,如果id已存在则后添加覆盖之前数据
'body' => [ 'first_name' => 'eeeee','age'=>10]
];
$client->index($params);
//批量新增
$response = $client->bulk($paramsb);
搜索高亮
$params = [
'index' => 'mysql_table_test',
'type' => 'out',
'body' => [
'query' => [
'bool' => [
'filter' => [
'term' => [ 'new_field' => 'abc' ]//过滤
],
'should' => [
[ 'match' => [ 'testfield' => '12345' ] ],
[ 'match' => [ 'name' => 'ok' ] ],
//模糊搜索
[ 'wildcard' => [ 'name' => 'e*'] ],] ] ],
'from'=>0, 'size'=>5, 'highlight' => [ 'pre_tags' => "<h1 style='color:red'>", 'post_tags' => "</h1>", 'fields' => [ "name" => new \stdClass(), "my_field" => new \stdClass(), ] ] ] ]; $results = $client->search($params);