广告
返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >PHP中使用ElasticSearch最新实例讲解
  • 161
分享到

PHP中使用ElasticSearch最新实例讲解

PHP中使用ElasticSearchPHP操作ElasticSearch 2022-11-11 23:11:38 161人浏览 独家记忆
摘要

网上很多关于ES的例子都过时了,版本很老,这篇文章的测试环境是es6.5 通过composer安装 composer require 'elasticsearch/elastic

网上很多关于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环境,当然环境只影响运行,不影响理解,包含基本的常用操作:    


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

class EsDemo {
	private $EsClient = null;
	private $faker = null;
	
	private $index = 'megacorp';
	private $type = 'employee';
	public function __construct(Faker $faker) {
		
		$this->EsClient = ClientBuilder::create()->setHosts(['172.16.55.53'])->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最新实例讲解的文章就介绍到这了,更多相关PHP中使用ElasticSearch最内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: PHP中使用ElasticSearch最新实例讲解

本文链接: https://www.lsjlt.com/news/121941.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作