Master Elasticsearch with PHP: From Basics to Real‑World Search Implementation
This guide explains why e‑commerce platforms need a high‑performance search engine, introduces Elasticsearch fundamentals, compares it with traditional engines, and provides step‑by‑step PHP code for installing, configuring, indexing, and querying data, complete with practical examples and best‑practice tips.
Background
E‑commerce growth creates massive data volumes and high‑concurrency search workloads that exceed the performance limits of traditional relational databases, motivating the adoption of a high‑performance, horizontally scalable search engine.
Introduction
Elasticsearch is an open‑source, distributed, RESTful full‑text search engine built on Apache Lucene. It indexes every field, scales to hundreds of nodes, and can store, search, and analyze terabytes of data in near real‑time.
Fundamentals
Concepts
Node and Cluster – the basic runtime units that cooperate to provide a unified search service.
Index – logical container for documents, analogous to a database.
Type and Document – older versions allowed multiple types per index; from 7.x only a single type is permitted, and types were removed in 8.x.
Shard and Replica – enable data distribution and fault tolerance.
Data Indexing
Mapping – defines field types, analyzers, and other properties.
Index Management – create, update mapping, and delete indices.
Search Techniques
Query DSL – a rich domain‑specific language for constructing complex queries.
Aggregations – provide analytics similar to SQL GROUP BY.
Elasticsearch vs. Traditional Search Engines
Traditional engines often rely on file‑system storage and NLP techniques, whereas Elasticsearch stores data in memory‑optimized structures and leverages Lucene for fast, scalable querying.
Indexing and Querying Principles
Indexing Process
Document parsing – convert fields and values into an internal representation.
Analysis – apply analyzers to text fields to produce searchable tokens.
Storage – write the processed data to on‑disk index files.
Query Process
Parsing – translate the request into a query object.
Search – retrieve matching documents from the index.
Sorting – order results according to specified criteria.
Highlighting – mark matching terms in the returned documents.
Operational Steps
Install and configure Elasticsearch.
Create an index.
Add documents to the index.
Execute search queries.
Update documents.
Delete documents.
Analyze query results.
Best Practices
Installation and Configuration
The example uses a managed Elasticsearch service compatible with the open‑source distribution.
Client SDK Installation
Install the official Elasticsearch PHP client:
composer require elasticsearch/elasticsearchElasticsearch PHP Client
Singleton client wrapper:
<?php
declare(strict_types=1);
namespace search;
use Elasticsearch\Client;
use Elasticsearch\ConnectionPool\SimpleConnectionPool;
class ElasticSearchClient {
protected static ?Client $instance = null;
private function __construct() {}
public static function getInstance(): ?Client {
if (self::$instance === null) {
self::$instance = \Elasticsearch\ClientBuilder::create()
->setHosts([
[
'host' => '127.0.0.1',
'port' => '9200',
'scheme' => 'http',
'user' => 'elastic',
'pass' => 'elastic'
]
])
->setConnectionPool(SimpleConnectionPool::class)
->setRetries(10)
->build();
}
return self::$instance;
}
}Document Model and Operations
Creating an index:
/**
* Create an index
*/
public function createIndex(): Response {
$client = ElasticSearchClient::getInstance();
$params = ['index' => 'resty_product_test_index'];
$resp = $client->indices()->create($params);
return response_json('success', 0, $resp);
}Adding a document:
/**
* Add a document to Elasticsearch
*/
public function addDocument(): Response {
$client = ElasticSearchClient::getInstance();
$data = [
'id' => 20245,
'title' => 'Open Source Tech Stack 20245 Live Room',
'content' => 'Open Source Tech Stack - Tencent Cloud Developer Community'
];
$params = [
'index' => 'resty_product_test_index',
'id' => $data['id'],
'body' => $data,
'client' => ['timeout' => 10, 'connect_timeout' => 10]
];
$resp = $client->index($params);
return response_json('success', 0, $resp);
}Sample add‑document response:
{
"code": 0,
"msg": "success",
"data": {
"_index": "resty_product_test_index",
"_type": "_doc",
"_id": "20245",
"_version": 1,
"result": "created",
"_shards": {"total": 2, "successful": 2, "failed": 0},
"_seq_no": 4,
"_primary_term": 1
}
}Searching documents:
/**
* Search documents
*/
public function searchDocument(): Response {
$client = ElasticSearchClient::getInstance();
$query = 'Open Source Tech Stack';
$params = [
'index' => 'resty_product_test_index',
'body' => [
'query' => [
'multi_match' => [
'query' => $query,
'fields' => ['title', 'content']
]
]
]
];
$resp = $client->search($params);
return response_json('success', 0, $resp);
}Sample search result:
{
"took": 12,
"timed_out": false,
"_shards": {"total": 1, "successful": 1, "skipped": 0, "failed": 0},
"hits": {
"total": {"value": 2, "relation": "eq"},
"max_score": 1.5399661,
"hits": [
{
"_index": "resty_product_test_index",
"_type": "_doc",
"_id": "20245",
"_score": 1.5399661,
"_source": {"id": 20245, "title": "Open Source Tech Stack 20245 Live Room", "content": "..."}
},
{
"_index": "resty_product_test_index",
"_type": "_doc",
"_id": "2024",
"_score": 1.5399661,
"_source": {"id": 2024, "title": "Open Source Tech Stack 2024 Live Room", "content": "..."}
}
]
}
}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.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
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.
