header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:POST,GET');
// 响应头
header("Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept");
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;
}
}
centos7 安装elasticsearch及elasticsearch-head
1.新增es用户并创建对应文件(/home/es data,logs等),修改/home/es的所有文件权限为es
2.visudo 新增 es ALL=(ALL) ALL
elasticearch下载地址https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.6.1
问题一:ERROR: bootstrap checks failed
vi /etc/security/limits.conf
添加如下内容:
- soft nproc 65536
- hard nproc 65536
- soft nofile 65536
- hard nofile 65536
问题二:max number of threads [1024] for user [lish] likely too low, increase to at least [2048]
解决:切换到root用户,进入limits.d目录下修改配置文件。
vi /etc/security/limits.d/90-nproc.conf
修改如下内容:
- soft nproc 1024
修改为
- soft nproc 2048
问题三:max virtual memory areas vm.max_map_count [65530] likely too low, increase to at least [262144]
vi /etc/sysctl.conf
添加下面配置:
vm.max_map_count=655360
最后并执行命令:
sysctl -p
3.上传elasticsearch安装包并修改配置文件
并在配置文件config/elasticsearch.yml末尾加上 (供elasticsearch-head访问使用)
http.cors.enabled: true
http.cors.allow-origin: “*”
后台启动elasticsearch /home/es/elasticsearch/bin/elasticsearch -d
4.打开网址查看es是否安装成功
http://localhost:9200/
5.安装elasticsearch-analysis-ik分词插件
/home/es/elasticsearch/bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.6.1/elasticsearch-analysis-ik-7.6.1.zip
6.安装elasticsearch-head https://www.jianshu.com/p/fdf90354e308
修改/home/es/elasticsearch-head/_site/app.js 内容中的localhost为当前服务器的ip地址,否则开启集群后显示未连接
后台启动elasticsearch-head nohup npm run start &
1.启动head:grunt server
2.查看head 进程:lsof -i :9100
3.停止head:kill -9 进程id
