当前位置: 首页 > news >正文

tp5集成elasticsearch笔记

  1. 安装Elasticsearch客户端
    首先需要通过Composer安装Elasticsearch PHP客户端,这里是7.0版本,
    Elasticsearch用的是
    Elasticsearch 7.17.x(最终维护版本)
    https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-17-10
    (推荐生产环境使用,7.x 的最后一个稳定版)
composer require elasticsearch/elasticsearch:^7.0

我用的windows版本,解压后双击这个目录下的这个bat文件
在这里插入图片描述
在浏览器里打开地址: http://localhost:9200/
显示:在这里插入图片描述
表示运行成功

  1. 配置Elasticsearch连接
    在config.php或新建一个配置文件(如elasticsearch.php)中添加配置:
// config/elasticsearch.php
return ['host' => ['http://localhost:9200', // ES服务器地址],'retries' => 1, // 重试次数'log_index' => 'tp5_logs', // 日志索引名称(可选)
];
  1. 创建服务类
    创建一个服务类来封装Elasticsearch操作:
// application/common/service/ElasticsearchService.php
namespace app\common\service;use Elasticsearch\ClientBuilder;
use think\Config;class ElasticsearchService
{private $client;public function __construct(){$config = Config::get('elasticsearch');$this->client = ClientBuilder::create()->setHosts($config['host'])->setRetries($config['retries'])->build();}/*** 创建索引*/public function createIndex($indexName, $mappings = []){$params = ['index' => $indexName,'body' => ['settings' => ['number_of_shards' => 1,'number_of_replicas' => 0],'mappings' => $mappings]];return $this->client->indices()->create($params);}/*** 添加/更新文档*/public function indexDocument($indexName, $id, $document){$params = ['index' => $indexName,'id'    => $id,'body'  => $document];return $this->client->index($params);}/*** 搜索文档*/public function search($indexName, $query){$params = ['index' => $indexName,'body'  => ['query' => $query]];return $this->client->search($params);}/*** 删除文档*/public function deleteDocument($indexName, $id){$params = ['index' => $indexName,'id'    => $id];return $this->client->delete($params);}// 其他Elasticsearch操作方法...
}
  1. 使用示例
    创建索引
$es = new \app\common\service\ElasticsearchService();
$mappings = ['properties' => ['title' => ['type' => 'text','analyzer' => 'ik_max_word','search_analyzer' => 'ik_max_word'],'content' => ['type' => 'text','analyzer' => 'ik_max_word','search_analyzer' => 'ik_max_word'],'create_time' => ['type' => 'date']]
];
$result = $es->createIndex('articles', $mappings);

添加文档

$document = ['title' => 'ThinkPHP5使用指南','content' => '这是一篇关于ThinkPHP5框架的使用教程...','create_time' => date('Y-m-d H:i:s')
];
$result = $es->indexDocument('articles', 1, $document);

搜索文档

$query = ['match' => ['title' => 'ThinkPHP5']
];
$result = $es->search('articles', $query);
  1. 高级用法
    批量操作
public function bulk($params)
{return $this->client->bulk($params);
}// 使用示例
$params = ['body' => []];
$data = [['id' => 1, 'title' => '文档1', 'content' => '内容1'],['id' => 2, 'title' => '文档2', 'content' => '内容2']
];foreach ($data as $item) {$params['body'][] = ['index' => ['_index' => 'articles','_id' => $item['id']]];$params['body'][] = ['title' => $item['title'],'content' => $item['content'],'create_time' => date('Y-m-d H:i:s')];
}$result = $es->bulk($params);

复杂查询

$query = ['bool' => ['must' => [['match' => ['title' => 'ThinkPHP']],['range' => ['create_time' => ['gte' => '2023-01-01','lte' => '2023-12-31']]]]]
];
$result = $es->search('articles', $query);
  1. 与模型结合
    可以创建一个基础模型类继承Elasticsearch功能:
// application/common/model/BaseEsModel.php
namespace app\common\model;use think\Model;
use app\common\service\ElasticsearchService;class BaseEsModel extends Model
{protected $esIndex;protected $esType = '_doc';protected $esService;protected function initialize(){$this->esService = new ElasticsearchService();}public function esSearch($query, $from = 0, $size = 10, $sort = []){$params = ['index' => $this->esIndex,'type'  => $this->esType,'body'  => ['query' => $query,'from'  => $from,'size'  => $size,'sort'  => $sort]];return $this->esService->search($params);}// 其他Elasticsearch相关方法...
}

注意事项
确保Elasticsearch服务已启动并正常运行

生产环境建议使用连接池和负载均衡配置多个节点

对于中文搜索,建议安装IK分词插件

大型应用考虑使用队列异步处理索引更新

注意异常处理,网络问题可能导致连接失败

通过以上步骤,你可以在ThinkPHP5中成功集成Elasticsearch,实现高效的全文搜索功能。

http://www.lryc.cn/news/620754.html

相关文章:

  • 开疆智能Ethernet转ModbusTCP网关连接UR机器人配置案例
  • ComfyUI工作流不动了?
  • OpenCV 形态学操作
  • Spring AI PagePdfDocumentReader 全解析:基于 Apache PdfBox 的按页 PDF 读取实战
  • COLMAP进行密集重建,三维重建的步骤
  • [机器学习]08-基于逻辑回归模型的鸢尾花数据集分类
  • AUTOSAR汽车电子嵌入式编程精讲300篇-【自动驾驶】硬件在环(HIL)(二)
  • 第四天~在CANFD或CAN2.0的ARXML文件中实现Multiplexor多路复用信号实战
  • 依托AR远程协助,沟通协作,高效流畅
  • 读From GPT-2 to gpt-oss: Analyzing the Architectural Advances
  • 第四天-创建一个Classic CAN(经典CAN2.0)/CANFD的系统描述ARXML文件
  • IDEA、Pycharm、DataGrip等激活破解冲突问题解决方案之一
  • 学习设计模式《二十二》——职责链模式
  • 深入了解linux系统—— 线程概念
  • 深入解析 Spring IOC 容器在 Web 环境中的启动机制
  • 嵌入式学习Day27
  • stm32项目(29)——基于stm32的智能眼镜设计
  • 【代码随想录day 20】 力扣 108.将有序数组转换为二叉搜索树
  • SwiftUI 页面弹窗操作
  • Linux网络编程:应用层自定义协议与序列化
  • Flutter sqflite插件
  • 支付域——账户系统设计
  • 支持pcm语音文件缓存顺序播放
  • 解剖HashMap的put <四> jdk1.8
  • OpenCv(二)——边界填充、阈值处理
  • Nacos 配置热更新:Spring Boot Bean 自动获取最新配置
  • flutter3.7.12版本设置TextField的contextMenuBuilder的文字颜色
  • MixOne在macOS上安装碰到的问题
  • 解决SQL Server连接失败:Connection refused: connect
  • 苹果正计划大举进军人工智能硬件领域