Home >Backend Development >PHP Tutorial >How to use PHP and Elasticsearch to display and navigate search results

How to use PHP and Elasticsearch to display and navigate search results

WBOY
WBOYOriginal
2023-07-18 11:13:27960browse

How to use PHP and Elasticsearch to display and navigate search results

With the rapid development of the Internet, search functions have become standard for various websites and applications. How to efficiently display search results and provide a good navigation experience has become an important challenge faced by website developers. This article will introduce how to use PHP and Elasticsearch to implement search results display and navigation functions.

1. Set up the development environment

First, we need to set up the development environment for PHP and Elasticsearch. Make sure you have installed PHP and Elasticsearch related packages.

2. Create an index

Before we begin, we need to create an index to store our data. Suppose we want to create a product search function, we can create an index called "products". In Elasticsearch, indexes are similar to tables in a database and are used to store and organize data.

Use the following code to create an index named "products":

<?php
require 'autoload.php';

use ElasticsearchClientBuilder;

$hosts = [
    'localhost:9200' // Elasticsearch的主机和端口
];

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

$params = [
    'index' => 'products' // 索引名称
];

$response = $client->indices()->create($params);

echo "Index created successfully.";
?>

3. Import data

Next, we need to import our data into the index we just created middle. In this example, we assume that we have a file named "products.json" that contains JSON data of some product information.

Use the following code to import data into the "products" index:

<?php
require 'autoload.php';

use ElasticsearchClientBuilder;

$hosts = [
    'localhost:9200' // Elasticsearch的主机和端口
];

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

$params = [
    'index' => 'products', // 索引名称
    'body'  => [
        // 导入数据的JSON数组
        [
            'index' => [
                '_index' => 'products',
                '_type'  => 'product',
            ]
        ],
        [
            'title'      => 'iPhone 11',
            'description' => 'An amazing smartphone by Apple.',
            'price'      => 999,
        ],
        [
            'index' => [
                '_index' => 'products',
                '_type'  => 'product',
            ]
        ],
        [
            'title'      => 'Samsung Galaxy S20',
            'description' => 'A powerful smartphone by Samsung.',
            'price'      => 899,
        ],
        // 更多商品数据...
    ]
];

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

echo "Data imported successfully.";
?>

4. Execute the search function

Now that we have created the index and imported the data, continue Then you can implement the search function. In PHP, we can use Elasticsearch’s Search API to perform search queries.

Use the following code to implement the search function:

<?php
require 'autoload.php';

use ElasticsearchClientBuilder;

$hosts = [
    'localhost:9200' // Elasticsearch的主机和端口
];

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

$params = [
    'index' => 'products', // 索引名称
    'body'  => [
        'query' => [
            'match' => [
                'title' => 'iPhone' // 搜索关键字
            ]
        ]
    ]
];

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

// 处理搜索结果
foreach ($response['hits']['hits'] as $hit) {
    echo $hit['_source']['title'] . "<br>";
    echo $hit['_source']['description'] . "<br>";
    echo $hit['_source']['price'] . "<br>";
    echo "<hr>";
}
?>

The above code uses Elasticsearch's "match" query to perform the search and traverse the search results for display.

5. Implement result paging and navigation

Generally speaking, the number of search results may be large, so we need to implement result paging and navigation functions to provide a better user experience . In PHP, we can use Elasticsearch's "from" and "size" parameters to implement paging.

Use the following code to implement paging and navigation functions:

<?php
require 'autoload.php';

use ElasticsearchClientBuilder;

$hosts = [
    'localhost:9200' // Elasticsearch的主机和端口
];

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

$page = isset($_GET['page']) ? intval($_GET['page']) : 1; // 当前页数
$perPage = 10; // 每页显示的数量

$from = ($page - 1) * $perPage;

$params = [
    'index' => 'products', // 索引名称
    'body'  => [
        'from' => $from, // 从第几个结果开始
        'size' => $perPage // 每页显示的数量
        'query' => [
            'match' => [
                'title' => 'iPhone' // 搜索关键字
            ]
        ]
    ]
];

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

// 处理搜索结果
foreach ($response['hits']['hits'] as $hit) {
    echo $hit['_source']['title'] . "<br>";
    echo $hit['_source']['description'] . "<br>";
    echo $hit['_source']['price'] . "<br>";
    echo "<hr>";
}

// 显示分页导航
$totalPages = ceil($response['hits']['total']['value'] / $perPage); // 总页数

for ($i = 1; $i <= $totalPages; $i++) {
    echo "<a href='search.php?page=$i'>$i</a>";
}
?>

The above code determines the current page number based on the user's request parameters, and uses the "from" and "size" parameters to control the range of results. . At the same time, the paginated navigation is calculated and displayed based on the total number of search results and the number displayed on each page.

Summary

This article introduces how to use PHP and Elasticsearch to realize the display and navigation functions of search results. By setting up a development environment, creating indexes, importing data, and executing search functions, we can achieve an efficient search experience and provide a better user experience through paginated navigation. I believe readers can easily apply it to their own projects based on the sample code in this article.

The above is the detailed content of How to use PHP and Elasticsearch to display and navigate search results. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn