Home >Backend Development >PHP Tutorial >How to build a multi-criteria search function using Elasticsearch and PHP
How to use Elasticsearch and PHP to build multi-condition search functions
Introduction:
Elasticsearch is an open source distributed search and analysis engine that is often used to build powerful search functions. It enables fast and accurate searches and supports various types of queries. This article will introduce how to use Elasticsearch and PHP to build multi-condition search functions, and provide corresponding code examples.
{ "require": { "elasticsearch/elasticsearch": "^7.0" } }
Then run the composer install
command to install the Elasticsearch PHP extension.
<?php require 'vendor/autoload.php'; use ElasticsearchClientBuilder; $hosts = [ 'http://localhost:9200' // Elasticsearch的访问地址 ]; $client = ClientBuilder::create()->setHosts($hosts)->build(); ?>
First, define an index configuration and mapping. For example, we create an index called "articles" and define the "article" type and specify the types of the "title" and "content" fields:
<?php $params = [ 'index' => 'articles', 'body' => [ 'mappings' => [ 'properties' => [ 'title' => ['type' => 'text'], 'content' => ['type' => 'text'] ] ] ] ]; $response = $client->indices()->create($params); ?>
Then, add documents to the index. For example, we add a document titled "News":
<?php $params = [ 'index' => 'articles', 'body' => [ 'title' => '新闻', 'content' => '这是一条新闻' ] ]; $response = $client->index($params); ?>
<?php $params = [ 'index' => 'articles', 'body' => [ 'query' => [ 'bool' => [ 'must' => [ ['match' => ['title' => '新闻']], ['match' => ['content' => '国际']] ] ] ] ] ]; $response = $client->search($params); ?>
Finally, iterate through the search results and print out the title and content of each document:
<?php foreach ($response['hits']['hits'] as $hit) { echo '标题:' . $hit['_source']['title'] . '<br>'; echo '内容:' . $hit['_source']['content'] . '<br>'; echo '----------------<br>'; } ?>
Conclusion:
Through the above steps, we can use Elasticsearch and PHP to build a multi-condition search function. First, install and configure Elasticsearch and the corresponding PHP extension; then, connect to Elasticsearch and create an index; finally, perform multi-condition search and process the search results.
Note: In order to ensure the accuracy and performance of the search, it is recommended to optimize the index before using multi-condition search, such as setting up a suitable word segmenter, building an index, etc.
Reference materials:
The above is the detailed content of How to build a multi-criteria search function using Elasticsearch and PHP. For more information, please follow other related articles on the PHP Chinese website!