木子李的个人博客

Good Luck To You!

thinkphp8 Elasticsearch7.15 使用及基本查询(二)

<?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

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2026年3月    »
1
2345678
9101112131415
16171819202122
23242526272829
3031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
    网站收藏
    友情链接

    Powered By Z-BlogPHP 1.7.3