将原始的elasticsearch-php库集成到Laravel 4.2中?

时间:2015-01-18 13:48:32

标签: php laravel laravel-4 elasticsearch

我是Laravel的第一天,我需要整合原始的elasticsearch-php库。 https://github.com/elasticsearch/elasticsearch-php

我是通过作曲家下载的,但不知道如何使用Laravel以正确的方式使用它。

基本上我想以这种方式使用它:

$ client = new ElasticSearch \ Client();

请帮忙。

1 个答案:

答案 0 :(得分:2)

将以下行添加到composer.json

"shift31/laravel-elasticsearch": "1.0.*@dev" "elasticsearch/elasticsearch": "~1.0"

按照https://github.com/shift31/laravel-elasticsearch#usage

上的其余安装说明进行操作

为了更好的衡量,我提供了一些初级样板代码,供您使用该库保存数据。

仅供参考,我使用我的环境来区分索引(生产或测试平台)。您可以使用其他方法,例如config.php值。

创建映射

$params = array();
$params['index'] = \App::environment();
//params' type and array body's 2nd element should be of the same name.
$params['type'] = 'car';
$params['body']['car'] = ['properties' => 
                            [
                            'id' => [
                                'type'  => 'long'
                            ],
                            'name' => [
                                'type'  =>  'string'
                            ],
                            'engine' => [
                                'type' => 'string'
                            ]
                        ];

$client = new Elasticsearch\Client();
$client->indices()->putMapping($params);

插入文档

$params = array();
$params['index'] = \App::environment();
$params['type'] = 'car';
$car = \CarModel::find($data['id']);
if(count($car))
{
    $params['id'] = $car->id;
    //Elasticsearch doesn't accept Carbon's default string value. Use the below function to convert it in an acceptable format.
    $params['timestamp'] = $car->updated_at->toIso8601String();
    // toArray will give you the attributes of the model AND its relations. This is the bothersome part where you will get more data than what you need.
    $params['body']['car'] = $car->toArray();
    \Es::index($params);
}

更新文件

$params = array();
$params['index'] = \App::environment();
$params['type'] = 'car';
$car = \CarModel::find($data['id']);
if(count($car))
{
    $params['id'] = $car->id;
    $params['body']['doc']['car'] = $car->toArray();
    \Es::update($params);
}

删除文档

$params = array();
$params['index'] = \App::environment();
$params['type'] = 'car';
$params['id'] = 1;
$deleteResult = $client->delete($params);