search
HomePHP FrameworkLaravelDetailed explanation of Laravel8 ES packaging and how to use it

This article will introduce you to the relevant knowledge about Laravel8, including explaining Laravel8 ES packaging and how to use it. I hope it will be helpful to everyone!

Detailed explanation of Laravel8 ES packaging and how to use it

[Related recommendations: laravel video tutorial

composer installation

composer require elasticsearch/elasticsearch

ES encapsulation

<?php
namespace App\Es;
use Elasticsearch\ClientBuilder;
class MyEs
{
    //ES客户端链接
    private $client;
    /**
     * 构造函数
     * MyElasticsearch constructor.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::create()->setHosts([&#39;127.0.0.1:9200&#39;])->build();
    }
    /**
     * 判断索引是否存在
     * @param string $index_name
     * @return bool|mixed|string
     */
    public function exists_index($index_name = &#39;test_ik&#39;)
    {
        $params = [
            &#39;index&#39; => $index_name
        ];
        try {
            return $this->client->indices()->exists($params);
        } catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }
    /**
     * 创建索引
     * @param string $index_name
     * @return array|mixed|string
     */
    public function create_index($index_name = &#39;test_ik&#39;) { // 只能创建一次
        $params = [
            &#39;index&#39; => $index_name,
            &#39;body&#39; => [
                &#39;settings&#39; => [
                    &#39;number_of_shards&#39; => 5,
                    &#39;number_of_replicas&#39; => 1
                ]
            ]
        ];
        try {
            return $this->client->indices()->create($params);
        } catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }
    /**
     * 删除索引
     * @param string $index_name
     * @return array
     */
    public function delete_index($index_name = &#39;test_ik&#39;) {
        $params = [&#39;index&#39; => $index_name];
        $response = $this->client->indices()->delete($params);
        return $response;
    }
    /**
     * 添加文档
     * @param $id
     * @param $doc [&#39;id&#39;=>100, &#39;title&#39;=>&#39;phone&#39;]
     * @param string $index_name
     * @param string $type_name
     * @return array
     */
    public function add_doc($id,$doc,$index_name = &#39;test_ik&#39;,$type_name = &#39;goods&#39;) {
        $params = [
            &#39;index&#39; => $index_name,
            &#39;type&#39; => $type_name,
            &#39;id&#39; => $id,
            &#39;body&#39; => $doc
        ];
        $response = $this->client->index($params);
        return $response;
    }
    /**
     * 判断文档存在
     * @param int $id
     * @param string $index_name
     * @param string $type_name
     * @return array|bool
     */
    public function exists_doc($id = 1,$index_name = &#39;test_ik&#39;,$type_name = &#39;goods&#39;) {
        $params = [
            &#39;index&#39; => $index_name,
            &#39;type&#39; => $type_name,
            &#39;id&#39; => $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 = &#39;test_ik&#39;,$type_name = &#39;goods&#39;) {
        $params = [
            &#39;index&#39; => $index_name,
            &#39;type&#39; => $type_name,
            &#39;id&#39; => $id
        ];
        $response = $this->client->get($params);
        return $response;
    }
    /**
     * 更新文档
     * @param int $id
     * @param string $index_name
     * @param string $type_name
     * @param array $body [&#39;doc&#39; => [&#39;title&#39; => &#39;苹果手机iPhoneX&#39;]]
     * @return array
     */
    public function update_doc($id = 1,$index_name = &#39;test_ik&#39;,$type_name = &#39;goods&#39;, $body=[]) {
        // 可以灵活添加新字段,最好不要乱添加
        $params = [
            &#39;index&#39; => $index_name,
            &#39;type&#39; => $type_name,
            &#39;id&#39; => $id,
            &#39;body&#39; => $body
        ];
        $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 = &#39;test_ik&#39;,$type_name = &#39;goods&#39;) {
        $params = [
            &#39;index&#39; => $index_name,
            &#39;type&#39; => $type_name,
            &#39;id&#39; => $id
        ];
        $response = $this->client->delete($params);
        return $response;
    }
    /**
     * 搜索文档 (分页,排序,权重,过滤)
     * @param string $index_name
     * @param string $type_name
     * @param array $body
     * $body = [
                &#39;query&#39; => [
                    &#39;match&#39; => [
                        &#39;fang_name&#39; => [
                            &#39;query&#39; => $fangName
                        ]
                    ]
                ],
                &#39;highlight&#39;=>[
                    &#39;fields&#39;=>[
                        &#39;fang_name&#39;=>[
                            &#39;pre_tags&#39;=>[
                                &#39;<span style="color: red">&#39;
                            ],
                            &#39;post_tags&#39;=>[
                                &#39;</span>&#39;
                            ]
                        ]
                    ]
                ]
            ];
     * @return array
     */
    public function search_doc($index_name = "test_ik",$type_name = "goods",$body=[]) {
        $params = [
            &#39;index&#39; => $index_name,
            &#39;type&#39; => $type_name,
            &#39;body&#39; => $body
        ];
        $results = $this->client->search($params);
        return $results;
    }
}

Add all the data in the data table to ES

public function esAdd()
    {
        $data = Good::get()->toArray();
        $es = new MyEs();
        if (!$es->exists_index(&#39;goods&#39;)) {
            //创建es索引,es的索引相当于MySQL的数据库
            $es->create_index(&#39;goods&#39;);
        }
        foreach ($data as $model) {
            $es->add_doc($model[&#39;id&#39;], $model, &#39;goods&#39;, &#39;_doc&#39;);
        }
    }

Every time a piece of data is added to MySQL, a piece of data is also added to es

Directly add the code to the logical method of adding MySQL to the database

        //添加至MySQL
        $res=Good::insertGetId($arr);
        $es = new MyEs();
        if (!$es->exists_index(&#39;goods&#39;)) {
            $es->create_index(&#39;goods&#39;);
        }
        //添加至es
        $es->add_doc($res, $arr, &#39;goods&#39;, &#39;_doc&#39;);
        return $res;

When modifying the MySQL data, the es data is also updated

Directly add the code to the logic of MySQL modifying the data In the method

      //修改MySQL的数据
        $res=Good::where(&#39;id&#39;,$id)->update($arr);
        $es = new MyEs();
        if (!$es->exists_index(&#39;goods&#39;)) {
            $es->create_index(&#39;goods&#39;);
        }
        //修改es的数据
        $es->update_doc($id, &#39;goods&#39;, &#39;_doc&#39;,[&#39;doc&#39;=>$arr]);
        return $res;

implement the search function through ES

public function search()
    {
        //获取搜索值
        $search = \request()->get(&#39;search&#39;);
        if (!empty($search)) {
            $es = new MyEs();
            $body = [
                &#39;query&#39; => [
                    &#39;match&#39; => [
                        &#39;title&#39; => [
                            &#39;query&#39; => $search
                        ]
                    ]
                ],
                &#39;highlight&#39;=>[
                    &#39;fields&#39;=>[
                        &#39;title&#39;=>[
                            &#39;pre_tags&#39;=>[
                                &#39;<span style="color: red">&#39;
                            ],
                            &#39;post_tags&#39;=>[
                                &#39;</span>&#39;
                            ]
                        ]
                    ]
                ]
            ];
            $res = $es->search_doc(&#39;goods&#39;, &#39;_doc&#39;, $body);
            $data = array_column($res[&#39;hits&#39;][&#39;hits&#39;], &#39;_source&#39;);
            foreach ($data as $key=>&$v){
                 $v[&#39;title&#39;] = $res[&#39;hits&#39;][&#39;hits&#39;][$key][&#39;highlight&#39;][&#39;title&#39;][0];
            }
            unset($v);
            return $data;
        }
        $data = Good::get();
        return $data;
    }

In addition, add es paging search

If it is used in the WeChat applet, use the pull-up to bottom Events

This function is implemented by adding code on top of the above search function

1. Receive the current page passed by the front-end applet

2. Call the es package When searching the method of the class, pass two more parameters

3. Add two formal parameters to the search method of the es package class

The search value will be highlighted after the search

If used in a WeChat applet, the label and value will be output directly to the page. Adding a label that parses rich text can convert the label into a format and achieve a highlighting effect

<rich-text nodes="{{item.title}}"></rich-text>

Original text Author: amateur

Reposted from the link: https://learnku.com/articles/66177

The above is the detailed content of Detailed explanation of Laravel8 ES packaging and how to use it. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Have you ever faced any challenges while working in distributed teams?Have you ever faced any challenges while working in distributed teams?Apr 29, 2025 am 12:35 AM

Thebiggestchallengeofmanagingdistributedteamsiscommunication.Toaddressthis,usetoolslikeSlack,Zoom,andGitHub;setclearexpectations;fostertrustandautonomy;implementasynchronousworkpatterns;andintegratetaskmanagementwithcommunicationplatformsforefficient

Full-Stack Development with Laravel: Managing APIs and Frontend LogicFull-Stack Development with Laravel: Managing APIs and Frontend LogicApr 28, 2025 am 12:22 AM

In Laravel full-stack development, effective methods for managing APIs and front-end logic include: 1) using RESTful controllers and resource routing management APIs; 2) processing front-end logic through Blade templates and Vue.js or React; 3) optimizing performance through API versioning and paging; 4) maintaining the separation of back-end and front-end logic to ensure maintainability and scalability.

Lost in Translation: Cultural Nuances and Misunderstandings in Distributed TeamsLost in Translation: Cultural Nuances and Misunderstandings in Distributed TeamsApr 28, 2025 am 12:22 AM

Totackleculturalintricaciesindistributedteams,fosteranenvironmentcelebratingdifferences,bemindfulofcommunication,andusetoolsforclarity.1)Implementculturalexchangesessionstosharestoriesandtraditions.2)Adjustcommunicationmethodstosuitculturalpreference

Measuring Connection: Analytics and Insights for Remote Communication EffectivenessMeasuring Connection: Analytics and Insights for Remote Communication EffectivenessApr 28, 2025 am 12:16 AM

Toassesstheeffectivenessofremotecommunication,focuson:1)Engagementmetricslikemessagefrequencyandresponsetime,2)Sentimentanalysistogaugeemotionaltone,3)Meetingeffectivenessthroughattendanceandactionitems,and4)Networkanalysistounderstandcommunicationpa

Security Risks in Distributed Teams: Protecting Data in a Remote WorldSecurity Risks in Distributed Teams: Protecting Data in a Remote WorldApr 28, 2025 am 12:11 AM

Toprotectsensitivedataindistributedteams,implementamulti-facetedapproach:1)Useend-to-endencryptionforsecurecommunication,2)Applyrole-basedaccesscontrol(RBAC)tomanagepermissions,3)Encryptdataatrestwithkeymanagementtools,and4)Fosterasecurity-consciousc

Beyond Email: Exploring Modern Communication Platforms for Remote CollaborationBeyond Email: Exploring Modern Communication Platforms for Remote CollaborationApr 28, 2025 am 12:03 AM

No, emailisnotthebostforremotecollaborationToday.Modern platformlack, Microsoft teams, Zoom, ASANA, AndTrelloFhertreal-Time Communication, Project management, Andintegrationfeaturesthancteamworkandefficiency.

Collaborative Document Editing: Streamlining Workflow in Distributed TeamsCollaborative Document Editing: Streamlining Workflow in Distributed TeamsApr 27, 2025 am 12:21 AM

Collaborative document editing is an effective tool for distributed teams to optimize their workflows. It improves communication and project progress through real-time collaboration and feedback loops, and common tools include Google Docs, Microsoft Teams, and Notion. Pay attention to challenges such as version control and learning curve when using it.

How long will the previous Laravel version be supported?How long will the previous Laravel version be supported?Apr 27, 2025 am 12:17 AM

ThepreviousversionofLaravelissupportedwithbugfixesforsixmonthsandsecurityfixesforoneyearafteranewmajorversion'srelease.Understandingthissupporttimelineiscrucialforplanningupgrades,ensuringprojectstability,andleveragingnewfeaturesandsecurityenhancemen

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.