编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Thinkphp Elasticsearch的基本使用方法

wxchong 2024-08-25 16:37:48 开源技术 12 ℃ 0 评论

前提:

1.正确安装 Elasticsearch Elasticsearch安装

2.正确安装 elasticsearch-php elasticsearch-php安装

3.正确安装 nginx+php+mysql+thinkcmf(类thinkphp框架) nginx+php+mysql安装

Thinkphp Elasticsearch的基本使用方法:

1.正确安装PHP环境后,本环境的测试地址为 http://192.168.1.108/

2.正确启动 Elasticsearch 及head插件 访问地址分别为:

http://192.168.1.109:9200/

http://192.168.1.109:9100/

3.上传 elasticsearch-php文件包 vendor 重命名为 Elsearch 到thinkcmf 目录 /www/simplewind/Core/Library/Vendor/ (/www/为程序根目录)

4.在 /www/application/Portal/Controller/ 中新建 ElsearchController.class.php 内容如下:

<?php

namespace Portal\Controller;

use Common\Controller\HomebaseController;

class ElsearchController extends HomebaseController {

private static $esClient;

/**

* 初始化连接

*/

public function __construct()

{

if (!self::$esClient) {

Vendor('Elsearch.autoload');

self::$esClient = \Elasticsearch\ClientBuilder::create()->setHosts(['192.168.1.109:9200'])->build();

}

}

public function createindex(){

$params = [

'index' => 'aaa',

'body' => [

'settings' => [

'number_of_shards' => 5, // 分片 默认5

'number_of_replicas' => 0 // 副本、备份 默认1

]

]

];

$response = self::$esClient->indices()->create($params);

return $response;

}

}

在浏览器中访问: http://192.168.1.108/index.php?m=elsearch&a=createindex

如果是elsearch6.0以下的版本,就可以正常创建索引,如果是6.0及以上版本会有如下错误:

找到错误所报的文件,找到 150行,在此处添加 'Content-Type' => ['application/json'], 修改后的文件为:

上传至服务器,再进行访问:http://192.168.1.108/index.php?m=elsearch&a=createindex ,访问正常,因为返回为空,所以页面空白。

再利用elsearch-head 插件来看添加的索引

创建索引成功。

接下来,添加文档到aaa索引中,在 ElsearchController.class.php 新建方法 adddoc,内容如图:

在浏览器中访问: http://192.168.1.108/index.php?m=elsearch&a=adddoc

通过head插件来看,aaa索引中有一个文档,点击 数据浏览可以看到 刚刚加的一条数据

接下来分别是修改文档,删除文档,删除索引的方法。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表