首页 > 编程语言 >php操作ElasticSearch搜索引擎流程详解

php操作ElasticSearch搜索引擎流程详解

时间:2023-02-05 21:11:06浏览次数:35  
标签:index name public 详解 params ElasticSearch php type id

目录
  • 一、安装
  • 二、使用
  • 三、新建ES数据库
  • 四、创建表
  • 五、插入数据
  • 六、 查询所有数据
  • 七、查询单条数据
  • 八、搜索
  • 九、测试代码

〝 古人学问遗无力,少壮功夫老始成 〞

如果这篇文章能给你带来一点帮助,希望给飞兔小哥哥一键三连,表示支持,谢谢各位小伙伴们。

 

一、安装

通过composer安装


composer require 'elasticsearch/elasticsearch'

 

二、使用

创建ES类


<?PHP
 
require 'vendor/autoload.php';
 
//如果未设置密码
$es = \Elasticsearch\ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->build();
 
//如果es设置了密码
$es = \Elasticsearch\ClientBuilder::create()->setHosts(['Http://username:[email protected]:9200'])->build()

 

三、新建ES数据库

index 对应关系型数据(以下简称Mysql)里面的数据库,而不是对应mysql里面的索引


<?php
$params = [
    'index' => 'autofelix_db', #index的名字不能是大写和下划线开头
    'body' => [
        'settings' => [
            'number_of_shards' => 5,
            'number_of_replicas' => 0
        ]
    ]
];
$es->indices()->create($params);

 

四、创建表

  • 在Mysql里面,光有了数据库还不行,还需要建立表,ES也是一样的
  • ES中的type对应MySQL里面的表
  • es6以前,一个index有多个type,就像MySQL中一个数据库有多个表一样
  • 但是ES6以后,每个index只允许一个type
  • 在定义字段的时候,可以看出每个字段可以定义单独的类型
  • 在first_name中还自定义了 分词器 ik,这是个插件,是需要单独安装的

<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    'body' => [
        'mytype' => [
            '_source' => [
                'enabled' => true
            ],
            'properties' => [
                'id' => [
                    'type' => 'integer'
                ],
                'first_name' => [
                    'type' => 'text',
                    'analyzer' => 'ik_max_word'
                ],
                'last_name' => [
                    'type' => 'text',
                    'analyzer' => 'ik_max_word'
                ],
                'age' => [
                    'type' => 'integer'
                ]
            ]
        ]
    ]
];
$es->indices()->putMapping($params);

 

五、插入数据

  • 现在数据库和表都有了,可以往里面插入数据了
  • 在ES里面的数据叫文档
  • 可以多插入一些数据,等会可以模拟搜索功能

<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    //'id' => 1, #可以手动指定id,也可以不指定随机生成
    'body' => [
        'first_name' => '飞',
        'last_name' => '兔',
        'age' => 26
    ]
];
$es->index($params);

 

六、 查询所有数据


<?php
$data = $es->search();
 
var_dump($data);

 

七、查询单条数据

  • 如果你在插入数据的时候指定了id,就可以查询的时候加上id
  • 如果你在插入的时候未指定id,系统将会自动生成id,你可以通过查询所有数据后查看其id

<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    'id' =>  //你插入数据时候的id
];
$data = $es->get($params);

 

八、搜索

ES精髓的地方就在于搜索


<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    'body' => [
        'query' => [
            'constant_score' => [ //非评分模式执行
                'filter' => [ //过滤器,不会计算相关度,速度快
                    'term' => [ //精确查找,不支持多个条件
                        'first_name' => '飞'
                    ]
                ]
            ]
        ]
    ]
];
 
$data = $es->search($params);
var_dump($data);

 

九、测试代码

基于Laravel环境,包含删除数据库,删除文档等操作


<?php
use Elasticsearch\ClientBuilder;
use Faker\Generator as Faker;
 

class EsDemo
{
    private $EsClient = null;
    private $faker = null;
 
    
    private $index = 'autofelix_db';
    private $type = 'autofelix_table';
 
    public function __construct(Faker $faker)
    {
        
        $this->EsClient = ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->build();
        
        $this->faker = $faker;
    }
 
    
    public function generateDoc($num = 100) {
        foreach (range(1,$num) as $item) {
            $this->putDoc([
                'first_name' => $this->faker->name,
                'last_name' => $this->faker->name,
                'age' => $this->faker->numberBetween(20,80)
            ]);
        }
    }
 
    
    public function delDoc($id) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' =>$id
        ];
        return $this->EsClient->delete($params);
    }
 
    
    public function search($query = [], $from = 0, $size = 5) {
//        $query = [
//            'query' => [
//                'bool' => [
//                    'must' => [
//                        'match' => [
//                            'first_name' => 'Cronin',
//                        ]
//                    ],
//                    'filter' => [
//                        'range' => [
//                            'age' => ['gt' => 76]
//                        ]
//                    ]
//                ]
//
//            ]
//        ];
        $params = [
            'index' => $this->index,
//            'index' => 'm*', #index 和 type 是可以模糊匹配的,甚至这两个参数都是可选的
            'type' => $this->type,
            '_source' => ['first_name','age'], // 请求指定的字段
            'body' => array_merge([
                'from' => $from,
                'size' => $size
            ],$query)
        ];
        return $this->EsClient->search($params);
    }
 
    
    public function getDocs($ids) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => ['ids' => $ids]
        ];
        return $this->EsClient->mget($params);
    }
 
    
    public function getDoc($id) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' =>$id
        ];
        return $this->EsClient->get($params);
    }
 
    
    public function updateDoc($id) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' =>$id,
            'body' => [
                'doc' => [
                    'first_name' => '张',
                    'last_name' => '三',
                    'age' => 99
                ]
            ]
        ];
        return $this->EsClient->update($params);
    }
 
    
    public function putDoc($body = []) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            // 'id' => 1, #可以手动指定id,也可以不指定随机生成
            'body' => $body
        ];
        $this->EsClient->index($params);
    }
 
    
    public function delAllIndex() {
        $indexList = $this->esStatus()['indices'];
        foreach ($indexList as $item => $index) {
            $this->delIndex();
        }
    }
 
    
    public function esStatus() {
        return $this->EsClient->indices()->stats();
    }
 
    
    public function createIndex() {
        $this->delIndex();
        $params = [
            'index' => $this->index,
            'body' => [
                'settings' => [
                    'number_of_shards' => 2,
                    'number_of_replicas' => 0
                ]
            ]
        ];
        $this->EsClient->indices()->create($params);
    }
 
    
    public function checkIndexExists() {
        $params = [
            'index' => $this->index
        ];
        return $this->EsClient->indices()->exists($params);
    }
 
    
    public function delIndex() {
        $params = [
            'index' => $this->index
        ];
        if ($this->checkIndexExists()) {
            $this->EsClient->indices()->delete($params);
        }
    }
 
    
    public function getMapping() {
        $params = [
            'index' => $this->index
        ];
        return $this->EsClient->indices()->getMapping($params);
    }
 
    
    public function createMapping() {
        $this->createIndex();
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => [
                $this->type => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
                        'id' => [
                            'type' => 'integer'
                        ],
                        'first_name' => [
                            'type' => 'text',
                            'analyzer' => 'ik_max_word'
                        ],
                        'last_name' => [
                            'type' => 'text',
                            'analyzer' => 'ik_max_word'
                        ],
                        'age' => [
                            'type' => 'integer'
                        ]
                    ]
                ]
            ]
        ];
        $this->EsClient->indices()->putMapping($params);
        $this->generateDoc();
    }
}
到此这篇关于php操作ElasticSearch搜索引擎流程详解的文章就介绍到这了。

标签:index,name,public,详解,params,ElasticSearch,php,type,id
From: https://www.cnblogs.com/dituirenwu/p/17093951.html

相关文章

  • block详解
    在网上搜关于block的知识都不是特别详细,在这里对block做一个详细的描述,从入门开始到满足日常大部分开发需要。block定义:block说白了就是一段代码块,提前存储一段代码,想要执行......
  • PHP中 empty() 和 isset() 的区别介绍
    目录二者共同点二者区别1、对于未设置的变量的判断2、对于""(空字符串)的判断3、对于0(作为整数的0)的判断4、对于0.0(作为浮点数的0)的判断5、对于"0"......
  • php去掉一维数组的键值的实例方法
    在PHP中,数组的每个元素都是由键值对(key-value)组成,通过元素的键名来访问对应键的值。提示:“索引”和“键名”指的是同一样东西,“索引”多指数组数字形式的下标。有时......
  • php7 安装mysqli实例讲解
    php7怎么安装Mysqli?Centosphp7安装mysqli扩展心得在新配服务器时发现,php无法连接到mysql。通过phpinfo发现。根本没有显示mysqli的相关配置。经过一系列研究。总结了......
  • PHP实现JWT的Token登录认证
    1、Jwt简介JSONWEBToken(缩写JWT),是目前最流行的跨域认证解决方案。session登录认证方案:用户从客户端传递用户名、密码等信息,服务端认证后将信息存储在session中,将sessi......
  • 腾讯出品小程序自动化测试框架【Minium】系列(五)API详解(中)
    写在前面又有好久没更新小程序自动化测试框架Minium系列文章了,主要真的太忙,尽量做到每周一更吧,还请大家能够理解!上篇文章为大家分享关于Minium中Minium、App模块的API ......
  • left join(左连接)、right join(右连接)、full join(全连接)、inner join(内连接)、cr
    (1)leftjoin(左连接)在两张表进行连接查询时,会返回左表所有的行数据,右表中返回只返回和左表匹配的数据,没有的显示为Null。(2)rightjoin(右连接)在两张表进行连接查询时,会返......
  • PHP7 preg_replace 出错及解决办法
    问题描述:PHP7废弃了preg_replace?原本是中php5中处理url中后面参数替换清除的,代码如下$url=preg_replace('/([?&])src=[^&]+(&?)/e','"$2"==""?"":"$1"',$url);但......
  • php实现ffmpeg处理视频的实践
    最近有一个项目需要使用FFmpeg处理视频,这里我写了一个demo,方便我们来实现视频操作ffmpeg操作demo<?PHPnamespace common\helpers;use common\models\Config;use ......
  • php中的标量数据类型总结
    php的数据类型可以分为三大类,分别是标量数据类型、复合数据类型和特殊数据类型。其中,标量数据类型是数据结构的最基础单元,只能存储一个数据。在 php 中的标量数据类型分......