Laravel full text searchelasticsearch

Posted by fpyontek on Sat, 02 Nov 2019 21:57:24 +0100

Using Elasticsearch search search engine, configure ik Chinese word segmentation, associate with Laravel model, and then realize the business logic of search. This is the end of the article. Use the Scout extension package of Laravel to complete the search function

To continue, Scout and Elastic enabled expansion packs have been installed and configured

Edit the Article model, add the LaravelScoutSearchable to the model you want to retrieve, and register a model observer to keep the model synchronized to the driver of the retrieval service:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Article extends Model
{
    // Introduce the trait, which registers a model observer to keep the model synchronized to the driver of the retrieval service
    use Searchable;

//...

    // Define the type in the index - the type in es is equivalent to the table in mysql
    public function searchableAs()
    {
        return 'article';
    }

    // Define which fields need to be searched
    public function toSearchableArray()
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content
        ];
     }

//...
}

Use the aritsan command to import existing data from mysql to ElasticSearch

php artisan scout:import

Check whether the configured index exists in ElasticSearch and the imported data size

curl 'localhost:9200/_cat/indices?v'

Some RESTful api calls of ElasticSearch can be used to test data

View index configuration

curl -XGET "http://localhost:9200/mi360?pretty=true"

View document list

curl -XGET "http://localhost:9200/mi360/_search?pretty=true"

View document with specified id=10

curl -XGET "http://localhost:9200/mi360/article/10?pretty=true"

ok! After importing successfully, start to write search business logic

Add routing

Route::get('/search', 'WelcomeController@search');

Edit the form form in the view file, submit it to the routing address, and the name of the input form = query

<form action="{{ url('/search') }}" class="search fr">
    <input type="text" name="query" placeholder="Sir, what do you want to search?">
    <button type="submit">search</button>
</form>

Write controller

public function search(Request $request)
{
    $this->validate($request, [
        'query' => 'required',
    ]);

    // Escaping Special Characters 
    $query = str_replace('/', '\/', strip_tags($request->get('query')));

    // Page by page, 10 items per page
    $articles = Article::search($query)->paginate(10);

    return view('welcome.search', compact('articles','query'));
}

Write a search presentation page

// Display search keywords and total number of items searched
<div class="head clearf">
    <h2 class="title fl active">
        Search:{{ $query }}
        <span class="search_count">(Search all together{{ $articles->total() }}Strip)</span>
    </h2>
</div>

// Traverse search results
<ul class="content">
    @foreach($articles as $article)
        <li class="item">
            <div class="row">
                <h3 class="title"><a
                            href="{{ route('articles.show', ['id' => $article->id]) }}">{{ $article->title }}</a>
                </h3>
            </div>
            <div class="row">
                <ul class="info">
                    <li>
                        <i></i>
                        <a href="{{ route('users.show', ['id' => $article->user->id, 'name' => $article->user->name]) }}">{{ $article->user->name }}</a>
                    </li>
                    <li>
                        <i></i>
                        {{ date('Y-m-d', strtotime($article->created_at)) }}
                    </li>
                    <li>
                        <i></i>
                        <a href="{{ route('articles.index', ['category' => $article->category->name]) }}">{{ $article->category->name }}</a>
                    </li>
                    <li>
                        <i></i>
                        @foreach($article->tags as $tag)
                            <a href="{{ route('articles.index', ['tag' => $tag->name]) }}">{{ $tag->name }}</a>
                        @endforeach
                    </li>
                </ul>
            </div>
            <div class="row">
                <div class="desc clearf">
                    <a href="{{ route('articles.show', ['id' => $article->id]) }}">
                        <img class="col-4 fl" src="{{ $article->pic }}" alt="{{ $article->title }}" title="{{ $article->title }}">
                    </a>
                    <div class="text col-8 fr">
                        {{ $article->intro }}
                    </div>
                    <div class="more">
                        <a href="{{ route('articles.show', ['id' => $article->id]) }}">Read the whole passage</a>
                    </div>
                </div>
            </div>
        </li>
    @endforeach
</ul>

// Show page codes
<div class="links">
    {{ $articles->links() }}
</div>

ok! So far, our website has added a full-text search server!

Source: http://www.mi360.cn/articles/40

Related articles:
11.Laravel full text search elastic search (1)
12.Laravel full text search elastic search (2)

Topics: PHP Laravel ElasticSearch curl