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 的最后一个稳定版)
javascript 复制代码
composer require elasticsearch/elasticsearch:^7.0

我用的windows版本,解压后双击这个目录下的这个bat文件

在浏览器里打开地址: http://localhost:9200/

显示:

表示运行成功

  1. 配置Elasticsearch连接
    在config.php或新建一个配置文件(如elasticsearch.php)中添加配置:
php 复制代码
// config/elasticsearch.php
return [
    'host' => [
        'http://localhost:9200', // ES服务器地址
    ],
    'retries' => 1, // 重试次数
    'log_index' => 'tp5_logs', // 日志索引名称(可选)
];
  1. 创建服务类
    创建一个服务类来封装Elasticsearch操作:
php 复制代码
// 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. 使用示例
    创建索引
php 复制代码
$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);

添加文档

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

搜索文档

php 复制代码
$query = [
    'match' => [
        'title' => 'ThinkPHP5'
    ]
];
$result = $es->search('articles', $query);
  1. 高级用法
    批量操作
php 复制代码
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);

复杂查询

php 复制代码
$query = [
    'bool' => [
        'must' => [
            ['match' => ['title' => 'ThinkPHP']],
            ['range' => [
                'create_time' => [
                    'gte' => '2023-01-01',
                    'lte' => '2023-12-31'
                ]
            ]]
        ]
    ]
];
$result = $es->search('articles', $query);
  1. 与模型结合
    可以创建一个基础模型类继承Elasticsearch功能:
php 复制代码
// 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,实现高效的全文搜索功能。

相关推荐
数智顾问17 小时前
【73页PPT】美的简单高效的管理逻辑(附下载方式)
大数据·人工智能·产品运营
和科比合砍81分18 小时前
ES模块(ESM)、CommonJS(CJS)和UMD三种格式
大数据·elasticsearch·搜索引擎
乖女子@@@19 小时前
React笔记_组件之间进行数据传递
javascript·笔记·react.js
瓦哥架构实战19 小时前
从 Prompt 到 Context:LLM OS 时代的核心工程范式演进
大数据
weixin_lynhgworld19 小时前
盲盒抽卡机小程序系统开发:以技术创新驱动娱乐体验升级
大数据·盲盒·抽谷机
要做朋鱼燕19 小时前
【C++】 priority_queue 容器模拟实现解析
开发语言·c++·笔记·职场和发展
ST.J19 小时前
swing笔记
java·笔记
TDengine (老段)20 小时前
TDengine 时间函数 TODAY() 用户手册
大数据·数据库·物联网·oracle·时序数据库·tdengine·涛思数据
四谎真好看21 小时前
Java 学习笔记(进阶篇2)
java·笔记·学习
悟乙己21 小时前
数据科学家如何更好地展示自己的能力
大数据·数据库·数据科学家