Hyperf 使用 Elasticsearch 增删改查基本方法

本文介绍了如何在Hyperf框架中利用Elasticsearch进行索引管理、文档操作,包括判断索引是否存在、创建索引、设置mapping、文档的增删改查以及查询数据的方法。示例代码详尽,适用于Elasticsearch和Hyperf的开发者。
摘要由CSDN通过智能技术生成

<?php

declare (strict_types = 1);

namespace App\Elasticsearch;

use Hyperf\Elasticsearch\ClientBuilderFactory;

use Hyperf\Utils\ApplicationContext;

class Elasticsearch

{

    /**

     * @var ContainerInterface

     */

    protected $container;

    protected $es_client;

 

    /**

     * 实例化客户端对象

     **/

    public function __construct()

    {

        $this->container = ApplicationContext::getContainer();

        $client_builder  = $this->container->get(ClientBuilderFactory::class);

 

        $builder = $client_builder->create();

        $host    = explode(',', config('es_host'));

 

        $this->es_client = $builder->setHosts($host)->build();

    }

 

    /**

     * 判断索引是否存在

     **/

    public function indexExistsEs($index)

    {

        $params = [

            'index' => $index,

        ];

        $result = $this->es_client->indices()->exists($params);

        return $result;

    }

 

    /**

     * 创建索引

     **/

    public function createIndex($index)

    {

        $params = [

            'index' => $index,

        ];

        $result = $this->es_client->indices()->create($params);

        return $result;

    }

 

    /**

     * 设置mapping

     **/

    public function putMapping($params)

    {

        extract($params);

        $mapping['index']      = $index;

        $mapping['type']       = $type;

        $field_type['keyword'] = [

            'type' => 'keyword',

        ];

        $field_type['text'] = [

            'type'            => 'text',

            'analyzer'        => 'ik_max_word',

            'search_analyzer' => 'ik_max_word',

        ];

        $data = [

            'properties' => value(function () use ($mapping_key, $field_type) {

                $properties = [];

                foreach ($mapping_key as $key => $value) {

                    if (empty($value)) {

                        continue;

                    }

                    foreach ($value as $cvalue) {

                        $properties[$cvalue] = $field_type[$key];

                    }

                }

                return $properties;

            })

        ];

     

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宁静之峰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值