elasticsearch简单的增删改查与高亮显示

原生方式 添加索引

$hosts = [
    '127.0.0.1:9200'
];
$client = \Elasticsearch\ClientBuilder::create()->setHosts($hosts)->build();

// 创建索引
$params = [
    'index' => 'goods',
    'body' => [
        'settings' => [
            'number_of_shards' => 5,
            'number_of_replicas' => 1
        ],
        'mappings' => [
            '_doc' => [
                '_source' => [
                    'enabled' => true
                ],
                'properties' => [
                    'title' => [
                        'type' => 'keyword'
                    ],
                    'desn' => [
                        'type' => 'text',
                        'analyzer' => 'ik_max_word',
                        'search_analyzer' => 'ik_max_word'
                    ]
                ]
            ]
        ]
    ]
];
$response = $client->indices()->create($params);

更新数据

$hosts = [
    '127.0.0.1:9200',
];
$client = \Elasticsearch\ClientBuilder::create()->setHosts($hosts)->build();
// 写文档
$params = [
    'index' => 'goods',
    'type' => '_doc',
    'id' => $model->id,
    'body' => [
        'title' => $model->title,
        'desn' => $model->desn,
    ],
];
$response = $client->index($params);

搜索数据

$hosts = [
    '127.0.0.1:9200',
];
$client = \Elasticsearch\ClientBuilder::create()->setHosts($hosts)->build();
$params = [
    'index' => 'goods',
    'type' => '_doc',
    'body' => [
        'query' => [
            'match' => [
                'title'=>[
                    'query' => '手机'
                ]
            ]
        ]
    ]
];
$results = $client->search($params);
dump($results);

 

 

 

封装方法使用

高亮显示

 public function search_doc()
    {
        $where='图形';
        $es = new ES('es');
        $index_name = "es";
        $type_name = "es";
        $body = [
            'query' => [
                'bool' => [
                    'should' => [
                        [
                            'match' => [
//                                搜索的字段名
                                'title' => [
                                    //搜索的关键字
                                    'query' => $where,
                                    'boost' => 4, // 权重大
                                ]
                            ],

                        ],
                        [
                            'match' => [
                                'content' => [
                                    'query' => $where,
                                    'boost' => 3, // 权重大
                                ]
                            ],

                        ],

                    ],
                ]

            ]];
        $response= $es->search_doc($index_name, $type_name, $body);
        $data  = array_column($response,"hits");
        $data  = array_column($data[0],"_source");
        foreach ($data as $key => &$val){
            $val['title']=str_replace($where,"<span style='color: red'>$where</span>",$val['title']);
        }
        //可以将数据发送到视图
        print_r($data);

 

 

简单的增删改查

<?php

namespace app\es\controller;

use app\common\lib\ES;

use NunoMaduro\Collision\Highlighter;
//use NunoMaduro\Collision\Contracts\Highlighter;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use Elasticsearch\ClientBuilder;

class Esone extends Controller
{


    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        //创建索引  索引名称不能重复 否则报错
        $es = new ES('es');
        //你要创建的索引名称
        $index_name = "es1";
        $es->create_index($index_name);
    }



    //添加数据
    public function create()
    {
        //
        $es = new ES('es');
        $params = [
            'index' => "es1",
            'id' => '1',
            'type' => "article",
            "body" => [
                "title" => "我是第一次添加的数据article1",
                'desn' => "我是第一次添加的数据desn1"]
        ];
        $es->add_doc($params);
    }

//    根据id修改es中的数据
    public function update()
    {
        //
        $es = new ES('es');
        $params = [
            'index' => "es1",
            'type' => "article",
            'id' => "1",
            "body" => [
                "doc" => [
                    "title" => "6100万颗心的共同记忆 再次C位亮相,闪耀全球!",
                    "desn" => "刚刚过去的这个清明节,与往年一样,有人凭寄哀思,有人缅怀忠魂。但也有一些瞬间,让人记起久久不能释怀,给这个特殊节气增添了一些格外不同的味道。"
                ]
            ]
        ];
        $es->update_doc($params);


    }

    //获取文档  搜索数据
    public function selects()
    {
        $es = new ES('es');
        $a = $es->get_doc('1', 'es1', 'article');
        dump($a);

    }

    //删除  根据id删除数据
    public function delete()
    {
        //
        $es = new ES('es');
        $a = $es->delete_doc('1', 'es1', 'article');
        //删除成功
        dump($a);

    }


    //表单实现数据添加


    public function add()
    {
        //渲染视图

        return view('inex');
    }

    public function addData(Request $request)
    {
        //接受数据
        $data = $request->param();
        //验证
        //添加数据
        //数据库
        try {
            //
            $data = \app\es\model\Es::create($data);
            //将数据添加到es中
            $es = new ES('es');
            $params = [
                //索引名
                'index' => "es",
                //相当于数据库
                'type' => "es",
                //id
                'id' => $data['id'],
                "body" => [
                    "title" => $data['title'],
                    "content" => $data['content'],
                    "desn" => $data['desn'],
                ]
            ];
            $es->add_doc($params);
        } catch (Exception $exception) {
            return join(['code' => 200, 'msg' => $exception->getMessage(), 'data' => ""]);
        }

        return join(['code' => 200, 'msg' => '添加成功', 'data' => $data]);
    }

    //查询数据 一条数据
    public function select(Request $request)
    {
        //要搜索的id值
        $id = '5';
        $es = new ES('es');
        //查询数据
        $a = $es->get_doc($id, 'es', 'es');
        print_r($a);
    }

    public function search_doc()
    {
        $where='图形';
        $es = new ES('es');
        $index_name = "es";
        $type_name = "es";
        $body = [
            'query' => [
                'bool' => [
                    'should' => [
                        [
                            'match' => [
//                                搜索的字段名
                                'title' => [
                                    //搜索的关键字
                                    'query' => $where,
                                    'boost' => 4, // 权重大
                                ]
                            ],

                        ],
                        [
                            'match' => [
                                'content' => [
                                    'query' => $where,
                                    'boost' => 3, // 权重大
                                ]
                            ],

                        ],

                    ],
                ]

            ]];
        $response= $es->search_doc($index_name, $type_name, $body);
        $data  = array_column($response,"hits");
        $data  = array_column($data[0],"_source");
        foreach ($data as $key => &$val){
            $val['title']=str_replace($where,"<span style='color: red'>$where</span>",$val['title']);
        }
        //可以将数据发送到视图
        print_r($data);

    }

}

 

posted @ 2021-04-13 17:57  Conqueror·  阅读(29)  评论(0编辑  收藏  举报