<?php
/**
* Created by PhpStorm.
* User: brady
* Date: 2018/4/8
* Time: 10:31
* esticsearch helper
*/ require APPPATH.'third_party/vendor/autoload.php'; use Elasticsearch\ClientBuilder; class O_es
{
protected $db_name;
protected $tb_name;
protected $client;
protected $host; //初始化
public function init($db_name,$tb_name)
{ try{
$this->db_name = $db_name;
$this->tb_name = $tb_name;
$this->host = config_item('db')['host'];
if(ENVIRONMENT !== 'development'){
$host=['172.18.30.69:9200'];
$this->client = ClientBuilder::create()->setHosts($host)->build();
} else {
$this->client = ClientBuilder::create()->build();
} return $this->client;
} catch(Exception $e){
$msg = $e->getMessage();
echo json_encode(['success'=>false,'msg'=>$msg]);exit;
}
} public function add_doc($id,$body=[])
{
$params = [
'index' => $this->db_name,
'type' => $this->tb_name,
'id' => $id,
'body' => $body
];
$response = $this->client->index($params);
if( isset($response['_shards']['successful']) && $response['_shards']['successful'] >0){
return true;
} else {
return false;
}
} //根据id获取完整的搜索结果
public function get_doc($id)
{ try{
$params = [
'index' => $this->db_name,
'type' => $this->tb_name,
'id' => (string)$id
]; $response = $this->client->get($params);
return $response;
} catch(Exception $e){
$msg = $e->getMessage();
echo json_encode(['success'=>false,'msg'=>$msg]);exit;
} } //根据id获取搜索结果
public function get_doc_source($id)
{
$params = [
'index' => $this->db_name,
'type' => $this->tb_name,
'id' => $id
]; $response = $this->client->getSource($params);
return $response;
} //文档搜索
public function search_index($search_index,$search_val)
{
try { $params = [
'index' => $this->db_name,
'type' => $this->tb_name,
'body' => [
'query' => [
'match' => [
$search_index => $search_val
]
]
]
]; $response = $this->client->search($params);
if($response['hits']['total'] > 0) {
return $response['hits']['hits'];
} else {
return false;//未搜索到
} } catch(Exception $e){
$msg = $e->getMessage();
echo json_encode(['success'=>false,'msg'=>$msg]);exit;
}
} public function search_index_mul($field,$string,$type='dis_max',$tie_breaker = 0.3)
{ try { foreach($field as $v){
$querys[] = ['match'=>[$v=>$string]];
} switch($type)
{
case 'dis_max':
{
$body = [
'query'=>[
$type=>[
'queries'=>[ ],
'tie_breaker'=>$tie_breaker
]
]
];
$body['query'][$type]['queries'] = $querys;
}
break; case 'bool':
{
$body = [
'query'=>[
$type=>[
'should'=>[ ]
]
]
];
$body['query'][$type]['should'] = $querys;
}
break; default :
{
$body = [
'query'=>[
$type=>[
'queries'=>[ ]
]
]
];
$body['query'][$type]['queries'] = $querys;
}
break; } $params = [
'index' => $this->db_name,
'type' => $this->tb_name,
'body' => $body
];
$response = $this->client->search($params);
if($response['hits']['total'] > 0) {
return $response['hits']['hits'];
} else {
return [];//未搜索到
} } catch(Exception $e){
$msg = $e->getMessage();
echo json_encode(['success'=>false,'msg'=>$msg]);exit;
}
} //文档删除
public function del_doc($id)
{
try{
$params = [
'index' => $this->db_name,
'type' => $this->tb_name,
'id' => (string)$id
];
$response = $this->client->delete($params);
return $response;
} catch(Exception $e){
$msg = $e->getMessage();
echo json_encode(['success'=>false,'msg'=>$msg]);exit;
}
} public function add_index()
{
$params = [
'index' => $this->db_name,
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
]
]
]; $response = $this->client->indices()->create($params);
print_r($response);
} public function del_index()
{
$deleteParams = [
'index' => $this->db_name
];
$response = $this->client->indices()->delete($deleteParams);
return $response;
} }

  

  $this->load->model("O_es");
$this->load->model("Tb_articles");
$this->O_es->init(config_item("db")['db'],'articles'); //$res = $this->Tb_articles->get_list(1,1000,'*','desc'); // $this->O_es->del_index();
// foreach($res as $v){
// $res = $this->O_es->add_doc($v['id'],$v);
// dump("索引".$v['id'].$res);
// } // $res = $this->O_es->add_doc('1',['testField' => 'hello 天安门']);
//$res = $this->O_es->add_doc('1',['title' => 'Quick brown rabbits','body'=>'Brown rabbits are commonly seen.']);
// $res = $this->O_es->add_doc('2',['title' => 'Keeping pets healthy','body'=>'My quick brown fox eats rabbits on a regular basis.']);
//dump($res);
$list = $this->O_es->search_index_mul(['title','content'],'bootstrap');
if(!empty($list))
{
foreach($list as $v){
dump($v['_source']);
}
}

  

elasticsearch 工具类的更多相关文章

  1. ElasticSearch 工具类封装(基于ElasticsearchTemplate)

    1.抽象接口定义 public abstract class SearchQueryEngine<T> { @Autowired protected ElasticsearchTempla ...

  2. elasticsearch java工具类

    docker运行elasticsearch docker pull elasticsearch:7.8.1 docker run -p 9200:9200 -p 9300:9300 -e " ...

  3. es2.4.6 java api 工具类

    网上找了很久没找到2.4.X 想要的java api 工具 自己写了一个,分享一下 导入所需的jar <!-- ElasticSearch begin --> <dependency ...

  4. Maven基础&&Spring框架阶段常用工具类整理

    常用工具类 1.密码加密工具类: package com.itheima.utils; import java.security.MessageDigest; import sun.misc.BASE ...

  5. elasticsearch通用工具类

    这几天写了一个关于es的工具类,主要封装了业务中常用es的常用方法. 本文中使用到的elasticsearch版本6.7,但实际上也支持es7.x以上版本,因为主要是对springboot提供的:El ...

  6. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  7. Android—关于自定义对话框的工具类

    开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...

  8. [转]Java常用工具类集合

    转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...

  9. js常用工具类.

    一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...

随机推荐

  1. Delphi 版FindWindow 和 FindWindowEx 的语法和用法

    FindWindow(lpClassName,        {窗口的类名}lpWindowName: PChar {窗口的标题}): HWND;              {返回窗口的句柄; 失败返 ...

  2. 微信订阅号 获取用户基本信息,登录及 php

    <?php //echo file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_cr ...

  3. 【Win10分区教程】

    Win10怎么分区?如何为Win10硬盘分区? 注:本教程适用于Win7.Win8.Win8.1和Win10系 到了Windows10时代,TB级硬盘已经很普及了,那么在Win10系统下如何为这些大容 ...

  4. js判断是否为数字

    function isNumber(value) { var patrn = /^(-)?\d+(\.\d+)?$/; if (patrn.exec(value) == null || value = ...

  5. IDEA项目启动报Unable to open debugger port (127.0.0.1:51554): java.net.SocketException "socket closed"

    启动报错: Unable to open debugger port (127.0.0.1:51554): java.net.SocketException "socket closed&q ...

  6. Angular : 绑定, 参数传递, 路由

    如何把jquery导入angular npm install jquery --savenpm install @type/jquery --save-dev "node_modules/z ...

  7. php开发aes加密总结

    <?php class Aes { /** * aes 加密 解密类库 * @by singwa * Class Aes *说明:本类只适用于加密字符串 * */ private $key = ...

  8. ruby Encoding

    一. 查看ruby支持的编码 Encoding.name_list 二. 搜索编码 Encoding.find('US-ASCII') #=> US-ASCII,不存在则抛出异常 三. __EN ...

  9. POJ2553 汇点个数(强连通分量

    The Bottom of a Graph Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 12070   Accepted: ...

  10. shell重温---基础篇(shell数组&数组操作)

    上篇博客已经分析重温了shell的运行方式以及其中的变量还有字符串,之后按照套路就是数组方面了,废话不多说,直接进入正题哈.(小白笔记,各位看官勿喷...)     bash shell呢,支持一位数 ...