Detailed 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!
[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(['127.0.0.1:9200'])->build(); } /** * 判断索引是否存在 * @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 (\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 = 'test_ik') { // 只能创建一次 $params = [ 'index' => $index_name, 'body' => [ 'settings' => [ 'number_of_shards' => 5, 'number_of_replicas' => 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 = 'test_ik') { $params = ['index' => $index_name]; $response = $this->client->indices()->delete($params); return $response; } /** * 添加文档 * @param $id * @param $doc ['id'=>100, 'title'=>'phone'] * @param string $index_name * @param string $type_name * @return array */ public function add_doc($id,$doc,$index_name = 'test_ik',$type_name = 'goods') { $params = [ 'index' => $index_name, 'type' => $type_name, 'id' => $id, 'body' => $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 = '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; } /** * 更新文档 * @param int $id * @param string $index_name * @param string $type_name * @param array $body ['doc' => ['title' => '苹果手机iPhoneX']] * @return array */ public function update_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods', $body=[]) { // 可以灵活添加新字段,最好不要乱添加 $params = [ 'index' => $index_name, 'type' => $type_name, 'id' => $id, 'body' => $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 = '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' => [ 'match' => [ 'fang_name' => [ 'query' => $fangName ] ] ], 'highlight'=>[ 'fields'=>[ 'fang_name'=>[ 'pre_tags'=>[ '<span style="color: red">' ], 'post_tags'=>[ '</span>' ] ] ] ] ]; * @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; } }
Add all the data in the data table to ES
public function esAdd() { $data = Good::get()->toArray(); $es = new MyEs(); if (!$es->exists_index('goods')) { //创建es索引,es的索引相当于MySQL的数据库 $es->create_index('goods'); } foreach ($data as $model) { $es->add_doc($model['id'], $model, 'goods', '_doc'); } }
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('goods')) { $es->create_index('goods'); } //添加至es $es->add_doc($res, $arr, 'goods', '_doc'); 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('id',$id)->update($arr); $es = new MyEs(); if (!$es->exists_index('goods')) { $es->create_index('goods'); } //修改es的数据 $es->update_doc($id, 'goods', '_doc',['doc'=>$arr]); return $res;
implement the search function through ES
public function search() { //获取搜索值 $search = \request()->get('search'); if (!empty($search)) { $es = new MyEs(); $body = [ 'query' => [ 'match' => [ 'title' => [ 'query' => $search ] ] ], 'highlight'=>[ 'fields'=>[ 'title'=>[ 'pre_tags'=>[ '<span style="color: red">' ], 'post_tags'=>[ '</span>' ] ] ] ] ]; $res = $es->search_doc('goods', '_doc', $body); $data = array_column($res['hits']['hits'], '_source'); foreach ($data as $key=>&$v){ $v['title'] = $res['hits']['hits'][$key]['highlight']['title'][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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.
