需要使用php处理elasticsearch,可在composer中找对应版本的类库: https://packagist.org/packages/elasticsearch/elasticsearch。我这里使用的是elasticsearch/elasticsearch: ~6.0,类库文件包大小1.5M左右。使用起来很简单方便:本文地址:http://www.04007.cn/article/844.html,未经许可,不得转载.
#php索引代码: $this->client = ClientBuilder::create()->setHosts($hostArr)->setRetries(2)->build(); #循环调用一下, 如果较多可批量调用另外也可考虑增量索引 $params = array( 'index' => 'test', 'type' => '_doc', 'body' => array( 'id' => $id, 'title' => $title, 'content' => $content, ) ); $response = $this->client->index($params); #搜索代码 $params = [ 'index' => 'my_index', 'body' => [ 'query' => [ 'match' => [ 'testField' => 'abc' ] ] ] ]; $response = $this->client->search($params); print_r($response);本文地址:http://www.04007.cn/article/844.html,未经许可,不得转载.
如果只是提供前台搜索,并且不想引入这么一个文件夹的话,可以直接写一个简单的class类实现一下即可。本文地址:http://www.04007.cn/article/844.html,未经许可,不得转载.
<?php /* * Note:elasticsearch服务层. * Author:04007 */ class Elasticsearch { public $server, $index, $url, $pagesize; private $type = '_doc'; //初始化一些配置及参数 public function __construct($pagesize=10, $index = 'oemu') { $_SERVER = array( 'http://192.168.162.11:9200', 'http://192.168.162.12:9200', 'http://192.168.162.13:9200' ); $this->index = $index; $this->server = $_SERVER[array_rand($_SERVER)]; $this->pagesize = $pagesize; $this->url = $this->server . '/' . $this->index . '/' . $this->type; } //search搜索标题内容字段并高亮 function search($q, $page=1) { $from = ($page-1) * $this->pagesize; $search = array( "query" =>array( "multi_match"=>array( "query"=> $q, "fields"=> array("title", "content") ) ), "highlight" => array( "pre_tags" => array("<span style=\"color:red;\">"), "post_tags"=> array("</span>"), "fields" => array( "title" => new \stdClass(), "content" => new \stdClass() ), "fragment_size"=>100, ), "from"=> $from, "size"=> $this->pagesize, ); $url = $this->url . '/_search'; return $this->request_post($url, $search); } //post data public function request_post($url, $param = []) { if (empty($param)) { return false; } $param = json_encode($param); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $param); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($param))); $data = curl_exec($ch); return json_decode($data, true); } //简单query public function query($q) { return $this->call('/_search?' . http_build_query(array('q' => $q))); } //call function public function call($path, $http = array()) { if (!$this->index) { throw new Exception('$this->index needs a value'); } return json_decode(file_get_contents( $this->server . '/' . $this->index . '/' . $this->type . $path, NULL, stream_context_create(array('http' => $http)) ), true); } }本文地址:http://www.04007.cn/article/844.html,未经许可,不得转载.
本文地址:http://www.04007.cn/article/844.html 未经许可,不得转载. 手机访问本页请扫描右下方二维码.
![]() |
![]() |
手机扫码直接打开本页面 |