1.在laravel的composer.json中添加
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.1.*",
"elasticsearch/elasticsearch": "~5.0"
}
2.执行composer更新
composer update
3.插入索引
<?php
namespace App\Http\Controllers;
//测试用
use Illuminate\Routing\Controller as BaseController;
use Elasticsearch\ClientBuilder;
class TestController extends BaseController
{
function test()
{
//测试使用es
$clientBuilder = ClientBuilder::create();
$hosts[] = "127.0.0.1";
$clientBuilder->setHosts($hosts);
$client = $clientBuilder->build();//初始化
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => '1',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);//添加索引
return json_encode($response);
}
}
返回值
{
"_index": "my_index",
"_type": "my_type",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
4.根据索引获取数据
$params = [
'index' => 'megacorp',
'type' => 'employee',
'id' => 4,
];
$response = $client->get($params);
{
"_index": "megacorp",
"_type": "employee",
"_id": "4",
"_version": 1,
"found": true,
"_source": {
"first_name": "tom",
"last_name": "john",
"age": 32,
"about": "I like to collect rock albums",
"interests": [
"music"
]
}
}
### 5.根据索引获取原始数据
$params = [
'index' => 'megacorp',
'type' => 'employee',
'id' => 4,
];
$response = $client->getSource($params);
>```
{
"first_name": "tom",
"last_name": "john",
"age": 32,
"about": "I like to collect rock albums",
"interests": [
"music"
]
}
6.条件查询
$params = [
'index' => 'megacorp',
'type' => 'employee',
'body' => [
'query' => [
'match' => [
'last_name' => 'john'
]
]
]
];
$response = $client->search($params);
{
"took": 20,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 0.2876821,
"hits": [
{
"_index": "megacorp",
"_type": "employee",
"_id": "4",
"_score": 0.2876821,
"_source": {
"first_name": "tom",
"last_name": "john",
"age": 32,
"about": "I like to collect rock albums",
"interests": [
"music"
]
}
},
{
"_index": "megacorp",
"_type": "employee",
"_id": "3",
"_score": 0.2876821,
"_source": {
"first_name": "Jane",
"last_name": "john",
"age": 32,
"about": "I like to collect rock albums",
"interests": [
"music"
]
}
}
]
}
}
### 7.删除文档
//删除一个文档
$params = [
'index' => 'megacorp',
'type' => 'employee',
'id' => 3
];
$response = $client->delete($params);
>```
{
"found": true,
"_index": "megacorp",
"_type": "employee",
"_id": "3",
"_version": 2,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
网友评论