es 7.15.2再laravel 使用
发布于 2 年前 作者 wei35 1932 次浏览 来自 分享

在    app/http/controllers/service   新建    Elasticsearch .php    直接封装代码

<?php

namespace App\Http\Controllers\service;

use Elasticsearch\ClientBuilder;

class ElasticsearchServier{

    //ES客户端链接

    private $client;

    /**

     * 初始化ES连接

     * ES constructor.

     */

    public function __construct($index)

    {

        $params = array(

            ‘127.0.0.1:9200’

        );

        $this->client = ClientBuilder::create()->setHosts($params)->build();

        // 查看是否建立索引,如果没有,则创建

        if (!$this->exists_index($index)) {

            $this->create_index($index);

        }

        return $this->client;

    }

    /**

     * 判断索引是否存在

     * @param string $index_name

     * @return bool|mixed|string

     */

    public function exists_index($index_name = ‘test_ik’)

    {

        $params = [

            ‘index’ => $index_name

        ];

        try {

            return $this->client->indices()->exists($params);

        } catch (\Exception $e) {

            return false;

        }

    }

    /**

     * 创建索引

     * @param string $index_name

     * @return array|mixed|string

     */

    public function create_index($index_name = ‘test_ik’)

    {

        // 只能创建一次

        $params = [

            ‘index’ => $index_name,

            ‘body’ => [

                ‘settings’ => [

                    ‘number_of_shards’ => 1,

                    ‘number_of_replicas’ => 1

                ]

            ]

        ];

        try {

            return $this->client->indices()->create($params);

        } catch (\Exception $e) {

            return false;

        }

    }

    /**

     * 删除索引

     * @param string $index_name

     * @return array

     */

    public function delete_index($index_name = ‘test_ik’)

    {

        $params = [‘index’ => $index_name];

        $response = $this->client->indices()->delete($params);

        return $response;

    }

    /**

     * 添加文档

     * @param $params

     * $params = [

     * ‘index’ => “es”,

     * ‘type’ => “article”,

     * “body” => [

     * “title” => “”,

     * ]

     * ];

     * @return array

     */

    public function add_doc($params)

    {

        return $this->client->index($params);

    }

    /**

     * 判断文档存在

     * @param int $id

     * @param string $index_name

     * @param string $type_name

     * @return array|bool

     */

    public function exists_doc($id = 1, $index_name = ‘test_ik’, $type_name = ‘goods’)

    {

        $params = [

            ‘index’ => $index_name,

            ‘type’ => $type_name,

            ‘id’ => $id

        ];

        $response = $this->client->exists($params);

        return $response;

    }

    /**

     * 获取文档

     * @param int $id

     * @param string $index_name

     * @param string $type_name

     * @return array

     */

    public function get_doc($id = 1, $index_name = ‘test_ik’, $type_name = ‘goods’)

    {

        $params = [

            ‘index’ => $index_name,

            ‘type’ => $type_name,

            ‘id’ => $id

        ];

        $response = $this->client->get($params);

        return $response;

    }

    /**

     * 修改文档

     *$params = [

    ‘index’ => “es”,

    ‘type’ => “article”,

    ‘id’ => “OIwzxXgBzF70K-DobSSC”,

    “body” => [

    “doc” => [

    “title” => “6100万颗心的共同记忆 再次C位亮相,闪耀全球!”,

    “desn” => “刚刚过去的这个清明节,与往年一样,有人凭寄哀思,有人缅怀忠魂。但也有一些瞬间,让人记起久久不能释怀,给这个特殊节气增添了一些格外不同的味道。”

    ]

    ]

    ];

     * @param array $params

     * @return array

     */

    public function update_doc($params = [])

    {

        $response = $this->client->update($params);

        return $response;

    }

    /**

     * 删除文档

     * @param int $id

     * @param string $index_name

     * @param string $type_name

     * @return array

     */

    public function delete_doc($id = 1, $index_name = ‘test_ik’, $type_name = ‘goods’)

    {

        $params = [

            ‘index’ => $index_name,

            ‘type’ => $type_name,

            ‘id’ => $id

        ];

        $response = $this->client->delete($params);

        return $response;

    }

    /**

     * 搜索文档 (分页,排序,权重,过滤)

     * @param string $index_name

     * @param string $type_name

     * @param array $body

     * $body = [

     * ‘query’ => [

     * ‘bool’ => [

     * ‘should’ => [

     * [

     * ‘match’ => [

     * ‘cate_name’ => [

     * ‘query’ => $keywords,

     * ‘boost’ => 4, // 权重大

     * ]

     * ]

     * ],

     * [

     * ‘match’ => [

     * ‘goods_name’ => [

     * ‘query’ => $keywords,

     * ‘boost’ => 3,

     * ]

     * ]

     * ],

     * [

     * ‘match’ => [

     * ‘goods_introduce’ => [

     * ‘query’ => $keywords,

     * ‘boost’ => 2,

     * ]

     * ]

     * ]

     * ],

     * ],

     * ],

     * ‘sort’ => [‘id’=>[‘order’=>‘desc’]],

     * ‘from’ => $from,

     * ‘size’ => $size

     * ];

     * @return array

     */

    public function search_doc($index_name = “test_ik”, $type_name = “goods”, $body = [])

    {

        $params = [

            ‘index’ => $index_name,

            ‘type’ => $type_name,

            ‘body’ => $body

        ];

        $results = $this->client->search($params);

        return $results;

    }

}

 App\Http\Controllers\mouth  建一个 ShowDataController控制器进行调用封装的代码

<?php

namespace App\Http\Controllers\mouth;

use App\Http\Controllers\Controller;

use App\Http\Controllers\service\ElasticsearchServier;

use App\Models\Title;

use Illuminate\Support\Facades\Request;

class ShowDataController extends Controller

{

    /**

     * 显示资源列表

     */

    public function index()

    {

        //创建索引  索引名称不能重复 否则报错

        $es = new ElasticsearchServier(‘ElasticsearchServier’);

//        你要创建的索引名称

        $indexNmae = ‘es_test’;

        $result = $es->create_index($indexNmae);

        return response()->json([‘code’ => 200, ‘messages’ => ‘索引创建成功’, ‘data’ => $result]);

    }

    /**

     * 添加数据

     */

    public function create()

    {

//        参数  相当于$request->post(‘title’)

        $title = ‘老人与海’;

        $content = ‘老人与海的文章内容’;

        $data = [

            ‘title’ => $title,

            ‘content’ => $content

        ];

        try {

            //添加至数据库中,并将id返回

            $id = Title::insertGetId($data);

            //将数据添加到es中

            $es = new ElasticsearchServier(‘ElasticsearchServier’);

            $params = [

                //索引名

                ‘index’ => “title”,

                //相当于数据库

                ‘type’ => “es”,

                //id

                ‘id’ => $id,

                “body” => [

                    “title” => $data[‘title’],

                    “content” => $data[‘content’],

                ]

            ];

            $es->add_doc($params);

        } catch (Exception $exception) {

            return response()->json([‘code’ => 200, ‘messages’ => ‘数据添加成功’, ‘data’ => $id]);

        }

        return response()->json([‘code’ => 200, ‘messages’ => ‘数据添加成功’, ‘data’ => $id]);

    }

    /**

     * 搜索

     */

    public function search_doc()

    {

        $where = ‘与海’;

        $es = new ElasticsearchServier(‘ElasticsearchServier’);

        $index_name = “title”;

        $type_name = “es”;

        $body = [

            ‘query’ => [

                ‘bool’ => [

                    ‘should’ => [

                        [

                            ‘match’ => [

//                                搜索的字段名

                                ‘title’ => [

                                    //搜索的关键字

                                    ‘query’ => $where,

                                    ‘boost’ => 4, // 权重大

                                ]

                            ],

                        ],

                        [

                            ‘match’ => [

                                ‘content’ => [

                                    ‘query’ => $where,

                                    ‘boost’ => 3, // 权重大

                                ]

                            ],

                        ],

                    ],

                ]

            ]];

        $response = $es->search_doc($index_name, $type_name, $body);

        $data = array_column($response, “hits”);

        $data = array_column($data[0], “_source”);

        foreach ($data as $key => &$val) {

            $val[‘title’] = str_replace($where, “<span style=‘color: red’>$where</span>”, $val[‘title’]);

        }

        //可以将数据发送到视图

        print_r($data);

    }

    /**

     * 查询一条数据

     */

    public function edit(Request $request)

    {

        //要搜索的id值

        $id = 3; //$request->get(‘id’);

        $es = new ElasticsearchServier(‘ElasticsearchServier’);

        //查询数据

        $edit = $es->get_doc($id, ‘title’, ‘es’);

        return response()->json([‘code’ => 200, ‘messages’ => ‘索引创建成功’, ‘data’ => $edit]);

    }

    /**

     *修改

     */

//    根据id修改es中的数据

    public function update()

    {

        $id = 3; //$request->get(‘id’);

        $title =‘610000万颗心的共同记忆 再次C位亮相,闪耀全球!’ ; //$request->get(‘title’);

        $content = ‘刚刚过去的这个清明节,与往年一样,有人凭寄哀思,有人缅怀忠魂。但也有一些瞬间’; //$request->get(‘id’);

        $es = new ElasticsearchServier(‘ElasticsearchServier’);

        $params = [

            ‘index’ => “title”,

            ‘type’ => “es”,

            ‘id’ => $id,

            “body” => [

                “doc” => [

                    “title” => $title,

                    “content” => $content

                ]

            ]

        ];

         $result=$es->update_doc($params);

        return response()->json([‘code’ => 200, ‘messages’ => ‘数据修改成功’, ‘data’ => $result]);

    }

}

回到顶部