Introduction to Elasticsearch and Its Integration with Laravel
This article explains Elasticsearch's foundation on Lucene, compares its concepts to MySQL, describes inverted indexing, and provides a step‑by‑step guide for installing, configuring, and using the basemkhirat/elasticsearch Laravel plugin with code examples and tips for Chinese analysis.
Elasticsearch is built on the open‑source Lucene library and wraps it with a RESTful API, making it ready to use without writing low‑level Lucene code.
Its core concepts can be likened to MySQL tables, as illustrated by a comparison diagram (not shown here).
To achieve fast full‑text search, Elasticsearch uses an inverted index; the article first explains forward (or "positive") indexes as the basis for building inverted indexes.
For Laravel integration, the basemkhirat/elasticsearch package is recommended. Install it via Composer: $ composer require basemkhirat/elasticsearch Then publish the service provider:
$ php artisan vendor:publish --provider="Basemkhirat\Elasticsearch\ElasticsearchServiceProvider"Configuration is added to the Laravel config file, defining connections, servers, and the default index:
'connections' => [
'default' => [
'servers' => [
[
"host" => env("ELASTIC_HOST", "127.0.0.1"),
"port" => env("ELASTIC_PORT", 9200),
'user' => env('ELASTIC_USER', ''),
'pass' => env('ELASTIC_PASS', ''),
'scheme' => env('ELASTIC_SCHEME', 'http'),
]
],
'index' => env('ELASTIC_INDEX', 'my_index')
]
],The plugin’s query methods mirror Laravel’s query builder, supporting where, whereIn, whereBetween, orderBy, first, get, and pagination via paginate.
Example to retrieve documents:
$documents = ES::connection("default")
->index("my_index")
->type("my_type")
->get(); // returns a collection of resultsField boosting can be set as follows:
ES::type("my_type")->search("hello", function($search){
$search->boost(2)->fields(["title" => 2, "content" => 1]);
})->get();For advanced queries, raw Elasticsearch DSL can be supplied directly:
$params['body'] = [
'aggs' => [
'all_created' => [
'terms' => [
'field' => 'element.raw',
'size' => $this->_mAggsPageSize,
],
'aggs' => [
'sum_pv' => [
'sum' => ['field' => 'pv'],
],
],
],
],
];In conclusion, Elasticsearch’s built‑in analyzers are not optimal for Chinese tokenization; the IK analyzer is recommended, and its version must match the Elasticsearch version used.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
