laravel:访问es,索引和搜索(Laravel 11.15.0)
一,安装需要的库
1,包的地址:
https://packagist.org/packages/elasticsearch/elasticsearch
2,文档地址:
https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html
3,用composer从命令行安装
[lhdop@blog dignews]$ composer require elasticsearch/elasticsearch
4,安装完成后查看所安装的版本:
[lhdop@blog dignews]$ composer show elasticsearch/elasticsearch
name : elasticsearch/elasticsearch
descrip. : PHP Client for Elasticsearch
keywords : client, elastic, elasticsearch, search
versions : * v8.14.0
type : library
license : MIT License (MIT) (OSI approved) https://spdx.org/licenses/MIT.html#licenseText
homepage :
二,添加controller和路由
1,添加controller
php artisan make:controller UserController
2,添加路由:routes/web.php
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function () {
Route::get('/user/home', 'home');
Route::get('/user/index', 'index');
Route::get('/user/getone', 'getone');
Route::get('/user/search', 'search');
});
三,索引功能/搜索功能
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Elastic\Elasticsearch\ClientBuilder;
class UserController extends Controller
{
//建立到es的连接
private function _init_es()
{
$hosts = ['127.0.0.1:9200'];
$client = ClientBuilder::create()->setHosts($hosts)->build();
return $client;
}
//直接返回字符串
public function home(){
$rand_digit = rand(100,999);
$msg = 'hello,随机数:'.$rand_digit;
return 'Hello, World!'.$msg;
}
//索引
public function index(){
//初始化一个es
$client = $this->_init_es();
$id=1;
$title = 'global world';
$content = 'man,good,linux,python';
$params = [
'index' => 'article1',
'id' => $id,
'body' => [
'id' => $id,
'title' => $title,
'content' => $content,
],
];
$rs = $client -> index($params);
print_r($rs);
}
//查询
public function getone() {
//初始化一个es
$client = $this->_init_es();
$id=1;
$params = [
'index' => 'article1',
//'type' => $type_name,
'id' => $id
];
$response = $client->get($params);
//print_r($response);
echo $response->getStatusCode(); // 200
//echo (string) $response->getBody(); // Response body in JSON
var_dump($response->asArray()); // response body content as array
}
//搜索
public function search() {
//初始化一个es
$client = $this->_init_es();
$params = [
'index' => 'article1',
'body' => [
'query' => [
'match' => [
'content' => 'linux'
]
]
]
];
$results = $client->search($params);
//var_dump($results->asArray()); // response body content as array
$ret = $results->asArray();
echo json_encode($ret);
}
}
四,测试效果
先索引后访问搜索地址的返回
五,查看laravel的版本:
[lhdop@blog dignews]$ php artisan --version
Laravel Framework 11.15.0