PHP调用Elasticsearch实现搜索功能
引言
在现代Web应用中,高效的搜索功能是提升用户体验的关键。Elasticsearch作为一款强大的分布式搜索引擎,被广泛应用于各种场景。本文将详细介绍如何使用PHP调用Elasticsearch来实现搜索功能。
环境准备
在开始之前,需要确保已经安装并配置好以下环境:
- PHP环境(推荐7.0及以上版本)
- Elasticsearch服务(推荐7.x版本)
- PHP的Elasticsearch客户端库(如elasticsearch/elasticsearch)
可以使用Composer来安装Elasticsearch客户端库:
composer require elasticsearch/elasticsearch
连接Elasticsearch
首先,需要在PHP代码中建立与Elasticsearch的连接。以下是一个简单的连接示例:
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
// 创建Elasticsearch客户端实例
$client = ClientBuilder::create()
->setHosts(['localhost:9200']) // 设置Elasticsearch服务器地址
->build();
// 测试连接
try {
$response = $client->info();
echo "Connected to Elasticsearch successfully!\n";
} catch (Exception $e) {
echo "Connection failed: " . $e->getMessage() . "\n";
}
?>创建索引
索引类似于数据库中的表,用于存储和组织数据。以下是创建一个名为"products"的索引的示例:
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
// 定义索引映射
$mapping = [
'index' => 'products',
'body' => [
'settings' => [
'number_of_shards' => 1,
'number_of_replicas' => 0
],
'mappings' => [
'properties' => [
'name' => ['type' => 'text'],
'description' => ['type' => 'text'],
'price' => ['type' => 'float'],
'category' => ['type' => 'keyword']
]
]
]
];
// 创建索引
try {
$response = $client->indices()->create($mapping);
echo "Index created successfully!\n";
} catch (Exception $e) {
echo "Error creating index: " . $e->getMessage() . "\n";
}
?>添加文档
向索引中添加文档,类似于向数据库表中插入记录。以下是添加产品文档的示例:
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
// 要添加的文档数据
$documents = [
[
'index' => 'products',
'id' => '1',
'body' => [
'name' => 'iPhone 13',
'description' => 'Apple iPhone 13 with A15 Bionic chip',
'price' => 999.99,
'category' => 'smartphone'
]
],
[
'index' => 'products',
'id' => '2',
'body' => [
'name' => 'Samsung Galaxy S21',
'description' => 'Samsung Galaxy S21 with Exynos 2100 processor',
'price' => 899.99,
'category' => 'smartphone'
]
]
];
// 批量添加文档
try {
$response = $client->bulk(['body' => $documents]);
echo "Documents added successfully!\n";
} catch (Exception $e) {
echo "Error adding documents: " . $e->getMessage() . "\n";
}
?>搜索文档
使用Elasticsearch进行搜索是其核心功能。以下是几种常见的搜索方式:
简单匹配搜索
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
// 构建搜索查询
$params = [
'index' => 'products',
'body' => [
'query' => [
'match' => [
'name' => 'iPhone'
]
]
]
];
// 执行搜索
try {
$response = $client->search($params);
echo "Search results:\n";
foreach ($response['hits']['hits'] as $hit) {
print_r($hit['_source']);
}
} catch (Exception $e) {
echo "Error searching: " . $e->getMessage() . "\n";
}
?>布尔搜索
布尔搜索允许组合多个条件。以下是一个示例,搜索名称包含"iPhone"且价格在800到1000之间的产品:
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
$params = [
'index' => 'products',
'body' => [
'query' => [
'bool' => [
'must' => [
['match' => ['name' => 'iPhone']]
],
'filter' => [
['range' => ['price' => ['gte' => 800, 'lte' => 1000]]]
]
]
]
]
];
try {
$response = $client->search($params);
echo "Boolean search results:\n";
foreach ($response['hits']['hits'] as $hit) {
print_r($hit['_source']);
}
} catch (Exception $e) {
echo "Error in boolean search: " . $e->getMessage() . "\n";
}
?>高亮显示搜索结果
为了提升用户体验,可以在搜索结果中高亮显示匹配的关键词。以下是如何实现高亮的示例:
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
$params = [
'index' => 'products',
'body' => [
'query' => [
'match' => [
'description' => 'Apple'
]
],
'highlight' => [
'fields' => [
'description' => new stdClass()
]
]
]
];
try {
$response = $client->search($params);
echo "Highlighted search results:\n";
foreach ($response['hits']['hits'] as $hit) {
echo "Name: " . $hit['_source']['name'] . "\n";
echo "Description: " . $hit['highlight']['description'][0] . "\n\n";
}
} catch (Exception $e) {
echo "Error in highlighted search: " . $e->getMessage() . "\n";
}
?>删除文档和索引
在某些情况下,可能需要删除文档或整个索引。以下是相关操作的示例:
删除文档
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
$params = [
'index' => 'products',
'id' => '1'
];
try {
$response = $client->delete($params);
echo "Document deleted successfully!\n";
} catch (Exception $e) {
echo "Error deleting document: " . $e->getMessage() . "\n";
}
?>删除索引
<?php
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
$params = ['index' => 'products'];
try {
$response = $client->indices()->delete($params);
echo "Index deleted successfully!\n";
} catch (Exception $e) {
echo "Error deleting index: " . $e->getMessage() . "\n";
}
?>总结
通过本文的介绍,我们了解了如何使用PHP调用Elasticsearch来实现搜索功能。从环境准备、连接Elasticsearch、创建索引、添加文档到执行各种搜索操作,以及高亮显示搜索结果和删除文档索引,涵盖了基本的搜索功能实现流程。在实际应用中,还可以根据具体需求进一步优化和扩展这些功能,例如实现更复杂的搜索查询、添加分页功能、优化性能等。