Elasticsearch基本的CURD

袁志蒙 1342次浏览

摘要:前面介绍过Elasticsearch是面向文档的存储引擎,存储的数据是以JSON文档为基本单位进行的,本文主要介绍在PHP中怎么对ES中文档的CRUD操作。...

前面介绍过Elasticsearch是面向文档的存储引擎,存储的数据是以JSON文档为基本单位进行的,本文主要介绍在PHP中怎么对ES中文档的CRUD操作。

1.什么是文档

在Elasticsearch中,文档其实就是一条JSON数据,SON数据格式可以非常复杂,也可以很简单。


2.什么是文档元数据

文档元数据,指的是插入JSON文档的时候,Elasticsearch为这条数据,自动生成的系统字段。

元数据的字段名都是以下划线开头的,常见的元数据如下:

_index - 代表当前JSON文档所属的文档名字

_type - 代表当前JSON文档所属的类型,虽然新版ES废弃了type的用法,但是元数据还是可以看到。

_id - 文档唯一Id, 如果我们没有为文档指定id,系统会自动生成

_source - 代表我们插入进去的JSON数据

_version - 文档的版本号,每修改一次文档数据,字段就会加1, 这个字段新版的ES已经不使用了

_seq_no - 文档的版本号, 替代老的_version字段

_primary_term - 文档所在主分区,这个可以跟_seq_no字段搭配实现乐观锁。

例如下面是从ES查询出来的一条文档的例子:

{
  "_index" : "order",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1, // 老ES版本的文档版本号,最新版本已经不使用了
  "_seq_no" : 0, // 新ES版本的文档版本号
  "_primary_term" : 1, // 主分区id
  "_source" : { // _source字段保存的就是我们插入到ES中的JSON数据
    "id" : 1,
    "status" : 1,
    "total_price" : 100,
    "create_time" : "2021-12-12 12:20:22",
    "user" : {
      "id" : 11,
      "username" : "yzmcms",
      "phone" : "18801108888",
      "address" : "北京市海淀区"
    }
  }
}

3.在PHP中操作ES:

在PHP中我们对ES进行操作时,我们要用到 elasticsearch-php 依赖包,在 composer.json 文件中引入 elasticsearch-php:

{
    "require": {
        "elasticsearch/elasticsearch": "~7.0"
    }
}

用 composer 安装客户端:

curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev

在项目中引入自动加载文件(如果还没引入),并且实例化一个客户端:

require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->build();

4.查询文档(基本查询):

$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 'my_id'
];

$response = $client->get($params);
print_r($response);

5.添加文档:

$params = [
	'body' => '我是内容',
	'id' => 'article_1',
	'index' => 'articles_index',
	'type' => 'articles_type'
];
//批量添加时,也可以使用 bulk 方法
$response = $this->client->index($params);
print_r($response);

6.删除文档:

$params = [
	'index' => 'articles_index',
	'type' => 'articles_type',
	'id' => 'article_1'
];
$response = $this->client->delete($params);
print_r($response)

7.更新文档:

$params = [
	'index' => 'articles_index',
	'type' => 'articles_type',
	'id' => 'article_1',
	'body' => [
		'doc' => [  // 必须带上这个.表示是文档操作
			'title' => '我是新的标题文档哈'
		]
	]
];
$response = $this->client->update($params);
print_r($response)


随机内容

表情

共0条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~