Current Location: Home> Latest Articles> Implementing Efficient Chinese Full-Text Search in PHP with Elasticsearch and IK Analyzer

Implementing Efficient Chinese Full-Text Search in PHP with Elasticsearch and IK Analyzer

gitbox 2025-08-06

Introduction

Elasticsearch is a powerful distributed full-text search engine capable of efficiently storing and querying large volumes of data. The IK Analyzer is specifically designed for Chinese, leveraging the unique characteristics of Chinese vocabulary to perform precise tokenization, thus improving search quality.

Elasticsearch Installation and Configuration

Installing Elasticsearch

You can download the appropriate installation package for your operating system from the Elasticsearch official website and follow the installation instructions:

wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.10.2-linux-x86_64.tar.gz

tar -zxvf elasticsearch-7.10.2-linux-x86_64.tar.gz

cd elasticsearch-7.10.2/bin

./elasticsearch

Configuring Elasticsearch

Edit the elasticsearch.yml configuration file and set the cluster name, node name, and network host as needed:

cluster.name: my_cluster

node.name: my_node

network.host: localhost

http.port: 9200

PHP Environment Setup

To use Elasticsearch in a PHP project, you need to install the official PHP client:

composer require elasticsearch/elasticsearch

Installing the IK Analyzer Plugin

The IK Analyzer provides support for Chinese segmentation. Install it with the following command:

cd elasticsearch-7.10.2/

./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.10.2/elasticsearch-analysis-ik-7.10.2.zip

Configuring the IK Analyzer

Add the following analyzer configuration to elasticsearch.yml:

index.analysis.analyzer.default.type: "ik_max_word"

index.analysis.analyzer.default.use_smart: "false"

Implementing Full-Text Search in PHP

The following example demonstrates how to perform full-text search using the PHP client:

$hosts = ['http://localhost:9200'];

$client = Elasticsearch\ClientBuilder::create()->setHosts($hosts)->build();

$params = [

    'index' => 'my_index',

    'body'  => [

        'query' => [

            'match' => [

                'content' => 'keyword'

            ]

        ]

    ]

];

$response = $client->search($params);

$results = $response['hits']['hits'];

The code above creates an Elasticsearch client instance, builds the query parameters, executes the search, and retrieves the matching results.

Conclusion

This article introduced how to implement Chinese full-text search in a PHP environment by combining Elasticsearch and the IK Analyzer plugin. With proper configuration and example code, developers can quickly build an efficient search service.