<?php
namespace app\controller;
use app\BaseController;
use app\common\Elasticsearch;
class Esearch extends BaseController
{
public $elasticsearch;
/**
* 构造方法
*/
public function __construct()
{
$this->elasticsearch = new Elasticsearch();
}
public function index()
{
$index = 'person';
$type = 'person_';
//设置索引
$this->elasticsearch->setIndex($index,$type);
//判断索引是否存在,不存在则创建
if($this->elasticsearch->existsIndex())
{
$this->elasticsearch->createIndex();
}
//获取映射 如果为空则创建
$mapping = $this->elasticsearch->getMapping();
if(empty($mapping[$index]['mappings'][$type])){
$params = [
'properties' => [
'id' => [
'type' => 'long', // 整型
],
'name' => [
//5.x以上已经没有string类型。如果需要分词的话使用text,不需要分词使用keyword。
'type' => 'text', // 字符串型
],
'age' => [
'type' => 'long',
],
'hobby' => [
'type' => 'text',
],
'introduction' => [
'type' => 'text',
],
]
];
$this->elasticsearch->createMappings($params);
}
//添加文档
$data = [
'id' => 5,
'name' => '张三',
'introduction' => '我是张三',
'age' => 30,
'hobby' => '程序员',
];
// $rs = $this->elasticsearch->addDoc(4,$data);
// var_dump($rs);
$arr=[];
for ($i=6;$i< 20;$i++){
$arr[]=[
'id' => $i,
'name' => '张三_'. $i,
'introduction' => '我是张三_'. $i,
'age' => 30 + $i,
'hobby' => '程序员_'. $i,
];
}
$body=[];
foreach ($arr as $k=>$v){
$body[($k*2)] = [
'index' => [
'_id' => $v['id'].'_'.$v['age'],
// '_type'=> $type,
'_index'=> $index
]
];
$body[(($k*2)+1)] = $v;
}
// $this->elasticsearch->addBulkDoc($body);
//获取文档
$data = $this->elasticsearch->searchDoc('张',0,3);
echo json_encode($data['hits']);die();
var_dump($data['hits']['hits']);
//var_dump($data['aggregations']['min']);
}
}引用来源csdn:https://blog.csdn.net/wyh757787026/article/details/137217496