thinkphp下使用elasticsearch搜索

<?php
namespace app\appapi\controller;
require '../vendor/autoload.php';
use Elasticsearch\ClientBuilder;
use think\Db;
use think\facade\Env;
use think\facade\Request;

class ElasticSearch
{
private $policy;
private $client;
private $index_name;
private $type_name;

// 构造函数
public function __construct()
{
require '../vendor/elasticsearch/elasticsearch/src/autoload.php';
$params = array(
Env::get('ELASTICSEARCHHOST', 'http://localhost:9200')
);

$project_area_id = get_area_ids();
$this->policy = Db::connect(config('database_policy.database'))->where('area_id', 'in', $project_area_id);
$this->client = ClientBuilder::create()->setHosts($params)->build();
$this->index_name = 'policy_xt';
$this->type_name = 'policy';
}

// 创建索引 只能创建一次
public function index()
{
$this->create_index(); //1.创建索引
$this->create_mappings(); //2.创建文档模板
$r = $this->bulk_index_doc();//3.插入数据
ajax_return([
'code' => 0,
'content' => $r
]);
}


// 政策匹配入口
public function go_search()
{
$params = Request::param();
$condition = [];
$condition['keywords'] = isset($params['keywords']) && !empty($params['keywords'])?$params['keywords']:'';
$condition['area_id'] = isset($params['area_id']) && !empty($params['area_id'])?$params['area_id']:0;
$condition['industryCategory'] = isset($params['industryCategory']) && !empty($params['industryCategory'])?$params['industryCategory']:'';


$from = isset($params['p'])?$params['p']:1;
$pageSize = 20;

$r = $this->search_doc($condition, $from, $pageSize); //4.搜索结果

ajax_return([
'code' => 0,
'content' => $r
]);
}

// 创建索引,只能创建一次
public function create_index()
{
$params = [
'index' => $this->index_name,
'body' => [
'settings' => [
'number_of_shards' => 1,
'number_of_replicas' => 0
]
]
];

try {
return $this->client->indices()->create($params);
} catch (Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
$msg = $e->getMessage();
$msg = json_decode($msg, true);
return $msg;
}
}

// 删除索引
public function delete_index()
{
$params = ['index' => $this->index_name];
$response = $this->client->indices()->delete($params);
return $response;
}

// 创建文档模板
public function create_mappings()
{

$params = [
'index' => $this->index_name,
'type' => $this->type_name,
'include_type_name'=>true,
'body' => [
$this->type_name => [
'_source' => [
'enabled' => true
],
'properties' => [
'id' => [
'type' => 'integer', // 整型
],
'title' => [
'type' => 'text', // 字符串型
'index' => 'true', // 全文搜索
'analyzer' => 'ik_smart',
'search_analyzer' => 'ik_smart'
],
'content' => [
'type' => 'text',
'index' => 'true',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
'area_id' => [
'type' => 'keyword',
'index' => 'true',
],
'industryCategory' => [
"type" => "text",
"analyzer" =>"ik_max_word",
],
'create_time' => [
'type' => 'integer',
],
]
]
]
];

$response = $this->client->indices()->putMapping($params);
return $response;
}

// 查看映射
public function get_mapping()
{
$params = [
'index' => $this->index_name,
'type' => $this->type_name,
];
$response = $this->client->indices()->getMapping($params);
return $response;
}

/*
* 批量(bulk)索引文档
* */
public function bulk_index_doc(){
$field = 'id, title, content, area_id, industryCategory, create_time';
// $list = $this->policy->name('policy_detail_resource')->field($field)->limit(50)->select();
$list = $this->policy->name('policy_detail_resource')->field($field)->select();
foreach ($list as $k => $v) {
$params['body'][] = [
'index' => [
'_index' => $this->index_name,
'_type' => $this->type_name,
]
];
$params['body'][] = [
'id' => $v['id'],
'title' => $v['title'],
'content' => $v['content'],
'area_id' => $v['area_id'],
'industryCategory' => $v['industryCategory'],
'create_time' => $v['create_time']
];
}

$ret = $this->client->bulk($params);
return $ret;
}


// 添加文档
public function add_doc($id, $doc)
{
$params = [
'index' => $this->index_name,
'type' => $this->type_name,
'id' => $id,
'body' => $doc
];

$response = $this->client->index($params);
return $response;
}

// 判断文档存在
public function exists_doc($id)
{
$params = [
'index' => $this->index_name,
'type' => $this->type_name,
'id' => $id
];

$response = $this->client->exists($params);
return $response;
}


// 获取文档
public function get_doc($id)
{
$params = [
'index' => $this->index_name,
'type' => $this->type_name,
'id' => $id
];

$response = $this->client->get($params);
return $response;
}

// 更新文档
public function update_doc($id, $doc)
{
// 可以灵活添加新字段,最好不要乱添加
$params = [
'index' => $this->index_name,
'type' => $this->type_name,
'id' => $id,
'body' => [
'doc' => [
'name' => $doc['name']
]
]
];

$response = $this->client->update($params);
return $response;
}

// 删除文档
public function delete_doc($id)
{
$params = [
'index' => $this->index_name,
'type' => $this->type_name,
'id' => $id
];

$response = $this->client->delete($params);
return $response;
}

// 查询文档 (分页,排序,权重,过滤)
public function search_doc(array $condition, $from=0, $size=20)
{

$params['index'] = $this->index_name;
$params['type'] = $this->type_name;
$params['_source'] = ['id', 'title', 'industryCategory', 'create_time'];//true则返回全部资源
$params['from'] = ($from-1)*$size;
$params['size'] = $size;

if(!empty($condition['keywords']))
{
$keywords = $condition['keywords'];

$params['body']['query']['bool']['should'][] = ['match' => ['title' => ['query' => $keywords,'boost' => 2]]];
$params['body']['query']['bool']['should'][] = ['match' => ['content' => ['query' => $keywords]]];
}

if(!empty($condition['area_id'])){
$params['body']['query']['bool']['must'][] = ['match'=>['area_id'=>$condition['area_id']]];
}

if(!empty($condition['industryCategory'])){
$params['body']['query']['bool']['must'][] = ['match'=>['industryCategory'=> $condition['industryCategory']]];
}

if(empty($condition)){
$params['body']['sort'] = ['id'=>['order'=>'desc']];
}

$results = $this->client->search($params);

$data = [];
foreach($results['hits']['hits'] as $r)
{
$data['data'][] = $r['_source'];
}

$totalRecords = $results['hits']['total']['value'];
$data['page'] = $from;
$data['pageSize'] = $size;
$data['totalPages'] = ceil($totalRecords/$size);
$data['totalRecords'] = $totalRecords;

return $data;
}


// 查询文档 (分页,排序,权重,过滤)备份
public function search_doc_copy(array $condition, $from = 0, $size = 20)
{

$params['index'] = $this->index_name;
$params['type'] = $this->type_name;
$params['from'] = $from;
$params['size'] = $size;
$params['sort'] = ['id' => ['order' => 'desc']];

if(!empty($condition['keywords']))
{
$keywords = $condition['keywords'];

// $params['body'] = [
// 'query' => [
// 'bool' => [
// 'should' => [
// ['match' => ['title' => [
// 'query' => $keywords,
// 'boost' => 2, // 权重大
// ]]],
// ['match' => ['content' => [
// 'query' => $keywords,
// ]]],
// ],
// ],
// ],
// 'sort' => ['id' => ['order' => 'desc']],
// 'from' => $from, 'size' => $size
// ];


$params['body']['query']['bool']['should'][] = ['match' => ['title' => ['query' => $keywords,'boost' => 2]]];
$params['body']['query']['bool']['should'][] = ['match' => ['content' => ['query' => $keywords]]];


// $params['body']['query'] = ['sort' => ['id' => ['order' => 'desc']]];
$params['body']['query']['sort']['id']['order'] = 'desc';
$params['body']['from'] = $from;
$params['body']['size'] = $size;
}

if(!empty($condition['area_id'])){
$params['body']['query']['match']['area_id'] = $condition['area_id'];
// $params['body']['query']['match'] = ['area_id' => $condition['area_id']];
}
if(!empty($condition['industryCategory'])){
$params['body']['query']['match']['industryCategory'] = $condition['industryCategory'];
// $params['body']['query']['match'] = ['industryCategory' => $condition['industryCategory']];
}

$results = $this->client->search($params);
return $results;
}

}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注