热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PHP中使用ElasticSearch最新实例讲解

这篇文章主要介绍了PHP中使用ElasticSearch最新实例讲解,这篇文章的教程是比较详细,有需要的同学可以研究下

网上很多关于ES的例子都过时了,版本很老,这篇文章的测试环境是ES6.5

通过composer安装

composer require 'elasticsearch/elasticsearch'

在代码中引入

require 'vendor/autoload.php';

use Elasticsearch\ClientBuilder;

$client = ClientBuilder::create()->setHosts(['172.16.55.53'])->build();

下面循序渐进完成一个简单的添加和搜索的功能。

首先要新建一个index:

index对应关系型数据(以下简称MySQL)里面的数据库,而不是对应MySQL里面的索引,这点要清楚

$params = [
  'index' => 'myindex', #index的名字不能是大写和下划线开头
  'body' => [
    'settings' => [
      'number_of_shards' => 2,
      'number_of_replicas' => 0
    ]
  ]
];
$client->indices()->create($params);

在MySQL里面,光有了数据库还不行,还需要建立表,ES也是一样的,ES中的type对应MySQL里面的表。

注意:ES6以前,一个index有多个type,就像MySQL中一个数据库有多个表一样自然,但是ES6以后,每个index只允许一个type,在往以后的版本中很可能会取消type。

type不是单独定义的,而是和字段一起定义

$params = [
  'index' => 'myindex',
  'type' => 'mytype',
  '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'
        ]
      ]
    ]
  ]
];
$client->indices()->putMapping($params);

在定义字段的时候,可以看出每个字段可以定义单独的类型,在first_name中还自定义了分词器 ik,

这个分词器是一个插件,需要单独安装的,参考另一篇文章:ElasticSearch基本尝试

现在数据库和表都有了,可以往里面插入数据了

概念:这里的 数据 在ES中叫文档

$params = [
  'index' => 'myindex',
  'type' => 'mytype',
  //'id' => 1, #可以手动指定id,也可以不指定随机生成
  'body' => [
    'first_name' => '张',
    'last_name' => '三',
    'age' => 35
  ]
];
$client->index($params);

多插入一点数据,然后来看看怎么把数据取出来:

通过id取出单条数据:

插曲:如果你之前添加文档的时候没有传入id,ES会随机生成一个id,这个时候怎么通过id查?id是多少都不知道啊。

所以这个插入一个简单的搜索,最简单的,一个搜索条件都不要,返回所有index下所有文档:

$data = $client->search();

现在可以去找一找id了,不过你会发现id可能长这样:zU65WWgBVD80YaV8iVMk,不要惊讶,这是ES随机生成的。

现在可以通过id查找指定文档了:

$params = [
  'index' => 'myindex',
  'type' => 'mytype',
  'id' =>'zU65WWgBVD80YaV8iVMk'
];
$data = $client->get($params);

最后一个稍微麻烦点的功能:

注意:这个例子我不打算在此详细解释,看不懂没关系,这篇文章主要的目的是基本用法,并没有涉及到ES的精髓地方,

ES精髓的地方就在于搜索,后面的文章我会继续深入分析

$query = [
  'query' => [
    'bool' => [
      'must' => [
        'match' => [
          'first_name' => '张',
        ]
      ],
      'filter' => [
        'range' => [
          'age' => ['gt' => 76]
        ]
      ]
    ]

  ]
];
$params = [
  'index' => 'myindex',
// 'index' => 'm*', #index 和 type 是可以模糊匹配的,甚至这两个参数都是可选的
  'type' => 'mytype',
  '_source' => ['first_name','age'], // 请求指定的字段
  'body' => array_merge([
    'from' => 0,
    'size' => 5
  ],$query)
];
$data = $this->EsClient->search($params);

上面的是一个简单的使用流程,但是不够完整,只讲了添加文档,没有说怎么删除文档,

下面我贴出完整的测试代码,基于Laravel环境,当然环境只影响运行,不影响理解,包含基本的常用操作:    

<&#63;php
use Elasticsearch\ClientBuilder;
use Faker\Generator as Faker;
/**
* ES 的 php 实测代码
*/
class EsDemo {
	private $EsClient = null;
	private $faker = null;
	/**
* 为了简化测试,本测试默认只操作一个Index,一个Type,
* 所以这里固定为 megacorp和employee
*/
	private $index = 'megacorp';
	private $type = 'employee';
	public function __construct(Faker $faker) {
		/**
* 实例化 ES 客户端
*/
		$this->EsClient = ClientBuilder::create()->setHosts(['172.16.55.53'])->build();
		/**
* 这是一个数据生成库,详细信息可以参考网络
*/
		$this->faker = $faker;
	}
	/**
* 批量生成文档
* @param $num
*/
	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)
			]);
		}
	}
	/**
* 删除一个文档
* @param $id
* @return array
*/
	public function delDoc($id) {
		$params = [
		'index' => $this->index,
		'type' => $this->type,
		'id' =>$id
		];
		return $this->EsClient->delete($params);
	}
	/**
* 搜索文档,query是查询条件
* @param array $query
* @param int $from
* @param int $size
* @return array
*/
	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);
	}
	/**
* 一次获取多个文档
* @param $ids
* @return array
*/
	public function getDocs($ids) {
		$params = [
		'index' => $this->index,
		'type' => $this->type,
		'body' => ['ids' => $ids]
		];
		return $this->EsClient->mget($params);
	}
	/**
* 获取单个文档
* @param $id
* @return array
*/
	public function getDoc($id) {
		$params = [
		'index' => $this->index,
		'type' => $this->type,
		'id' =>$id
		];
		return $this->EsClient->get($params);
	}
	/**
* 更新一个文档
* @param $id
* @return array
*/
	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);
	}
	/**
* 添加一个文档到 Index 的Type中
* @param array $body
* @return void
*/
	public function putDoc($body = []) {
		$params = [
		'index' => $this->index,
		'type' => $this->type,
		// 'id' => 1, #可以手动指定id,也可以不指定随机生成
		'body' => $body
		];
		$this->EsClient->index($params);
	}
	/**
* 删除所有的 Index
*/
	public function delAllIndex() {
		$indexList = $this->esStatus()['indices'];
		foreach ($indexList as $item => $index) {
			$this->delIndex();
		}
	}
	/**
* 获取 ES 的状态信息,包括index 列表
* @return array
*/
	public function esStatus() {
		return $this->EsClient->indices()->stats();
	}
	/**
* 创建一个索引 Index (非关系型数据库里面那个索引,而是关系型数据里面的数据库的意思)
* @return void
*/
	public function createIndex() {
		$this->delIndex();
		$params = [
		'index' => $this->index,
		'body' => [
		'settings' => [
		'number_of_shards' => 2,
		'number_of_replicas' => 0
		]
		]
		];
		$this->EsClient->indices()->create($params);
	}
	/**
* 检查Index 是否存在
* @return bool
*/
	public function checkIndexExists() {
		$params = [
		'index' => $this->index
		];
		return $this->EsClient->indices()->exists($params);
	}
	/**
* 删除一个Index
* @return void
*/
	public function delIndex() {
		$params = [
		'index' => $this->index
		];
		if ($this->checkIndexExists()) {
			$this->EsClient->indices()->delete($params);
		}
	}
	/**
* 获取Index的文档模板信息
* @return array
*/
	public function getMapping() {
		$params = [
		'index' => $this->index
		];
		return $this->EsClient->indices()->getMapping($params);
	}
	/**
* 创建文档模板
* @return void
*/
	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最新实例讲解的文章就介绍到这了,更多相关PHP中使用ElasticSearch最内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文由编程笔记小编整理,介绍了PHP中的MySQL函数库及其常用函数,包括mysql_connect、mysql_error、mysql_select_db、mysql_query、mysql_affected_row、mysql_close等。希望对读者有一定的参考价值。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 解决VS写C#项目导入MySQL数据源报错“You have a usable connection already”问题的正确方法
    本文介绍了在VS写C#项目导入MySQL数据源时出现报错“You have a usable connection already”的问题,并给出了正确的解决方法。详细描述了问题的出现情况和报错信息,并提供了解决该问题的步骤和注意事项。 ... [详细]
  • 本文介绍了关于apache、phpmyadmin、mysql、php、emacs、path等知识点,以及如何搭建php环境。文章提供了详细的安装步骤和所需软件列表,希望能帮助读者解决与LAMP相关的技术问题。 ... [详细]
  • 众筹商城与传统商城的区别及php众筹网站的程序源码
    本文介绍了众筹商城与传统商城的区别,包括所售产品和玩法不同以及运营方式不同。同时还提到了php众筹网站的程序源码和方维众筹的安装和环境问题。 ... [详细]
  • Windows简单部署Exceptionless
    部署准备Elasticsearch、Exceptionless.API、Exceptionless.UI、URLRewrite、.NET运行时 1、安装ElasticSearch1 ... [详细]
  • 我在MySQL中有一个很大的字段,并且不想将原始值保存到ElasticSearch。是否有像LuceneField.Stor ... [详细]
author-avatar
迷蒙的天蝎
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有