Install Elasticsearch
1. First, you must have a JDK environment to ensure that JDK8 and above version
1.1: You need a registered account to download, you can register yourself, or you can search for an account online
https://www.oracle.com/java/technologies/javase-jdk11-downloads.html
1.2: Configure environment variables: create a variable JAVA_HOME, the value is the path where you install jdk
Then edit path to add variable
2: Install Elasticsearch service, select window. (Here I installed version 6.8.8)
https://www.elastic.co/cn/downloads/past-releases#elasticsearch
2.1: After downloading, enter the bin directory and click elasticsearch.bat (do not close it in the window system)
2.2: Visit http://localhost:9200/, and the Elasticsearch service installation is complete.
The detailed configuration can be viewed in the official document.
https://www.elastic.co/guide/en/elasticsearch/reference/6.8/getting-started.html
elasticsearch-php installation and use
1: The installation of Elasticsearch-php needs to meet the following 4 requirements:
- PHP 7.0.0 or higher
- Composer
- ext-curl: Libcurl extension for PHP
- Native JSON extension (ext-json) 1.3.7 or higher
1.1: After cd to your project,
replace the composer mirror address, then execute:
composer -g config repo.packagist composer https://packagist.phpcomposer.com
Execute the following command to install
composer require elasticsearch/elasticsearch
After Elasticsearch-php is installed, the following directories and files will be generated in the current directory: composer.json, composer.lock, vendor/
Use script example
<?php
require 'vendor/autoload.php';
$client = new Elasticsearch\Client();
2: Case (mysql)
2.1: Create database (elastic) and table (articles) data test:
create table articles(
id int not null primary key auto_increment,
title varchar(200) not null comment '标题',
content text comment '内容',
price int not null comment '金额'
);
insert into articles(title, content) values ('李白', '酒仙刺客',100),
('孙悟空', '腾云驾雾的辜负了紫霞的刺客。',300),
('胡歌', '尽职励志,不错哦。',1000000),
('王者荣耀', '游戏就玩王者荣耀。',98),
('鲁班', '小短腿,谁都想灭。',998),
('妲己', '祸国殃民。',998),
('吕布', '方天画戟,后手放大',2998),
('水晶', '保护我方水晶,进攻地方水晶。',19999);
2.2: php uses Elasticsearch-php
<?php
require './vendor/autoload.php';
use Elasticsearch\ClientBuilder;
class ES {
private $client;
public function __construct(){
$params = array(
'127.0.0.1:9200'
);
$this->client = ClientBuilder::create()->setHosts($params)->build();
}
//创建索引
function createIndex($index_name = 'aki'){
$params = [
'index' => $index_name,
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
],
]
];
return $this->client->indices()->create($params);
}
//是否存在索引
public function existsIndex($index_name = 'aki'){
$params = ['index' => $index_name];
if($this->client->indices()->exists($params)){
return true;
}
return false;
}
// 删除索引
public function delIndex($index_name = 'aki') {
$params = ['index' => $index_name];
if($this->client->indices()->exists($params)){
$this->client->indices()->delete($params);
// echo "true";
return true;
}
// echo "false";
return false;
}
// 添加文档
public function addDoc($id,$doc,$index_name = 'aki',$type_name = 'form') {
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id,
'body' => $doc
];
return $this->client->index($params);
}
// 判断文档存在
public function existsDoc($id = 1,$index_name = 'aki',$type_name = 'form') {
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id
];
return $this->client->exists($params);
}
// 获取文档
public function getDoc($id = 1,$index_name = 'aki',$type_name = 'form') {
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id
];
return $this->client->get($params);
}
// 更新文档
public function updateDoc($id,$doc,$index_name = 'aki',$type_name = 'form') {
// 可以灵活添加新字段,最好不要乱添加
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id,
'body' => [
'doc' =>$doc
]
];
return $this->client->update($params);
}
// 删除文档
public function delDoc($id,$index_name = 'aki',$type_name = 'form') {
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id
];
return $this->client->delete($params);
}// 查询文档 (分页,排序,权重,过滤)
public function searchDoc($keywords = "竞赛",$index_name = "aki",$type_name = "form",$sort = [],$from = 0,$size = 10) {
$params = [
'index' => $index_name,
'type' => $type_name,
'body' => [
'query' => [
'bool' => [
'should' => [
[ 'match' => [ 'title' => [
'query' => $keywords,
'boost' => 3, // 权重大
]]],
[ 'match' => [ 'content' => [
'query' => $keywords,
'boost' => 2,
]]],
],
],
],
// 'sort' => ['prices'=>['order'=>'desc']],
'from' => $from, 'size' => $size
]
];
$results = $this->client->search($params);
// $maxScore = $results['hits']['max_score'];
// $score = $results['hits']['hits'][0]['_score'];
// $doc = $results['hits']['hits'][0]['_source'];
return $results['hits']['hits'];
}
}
//--------------------------------------------------------------------------------------------
//测试实例:
$es = new ES();
//使用mysql测试
// $es->delIndex("mysql");
// $es->createIndex("mysql"); //创建索引
$ismysql = false;
if($ismysql == true){
// $es->delIndex("mysql");
$isidnex = $es->existsIndex("mysql");
if($isidnex == false){
$es->createIndex("mysql"); //创建索引
}
try {
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "elastic";
// // 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "select * from articles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// // 输出数据
while($row = $result->fetch_assoc()) {
// if(empty($es->getDoc($row['id'],"mysql"))){
// $es->addDoc($row['id'],$row,"mysql");
// }
$es->addDoc($row['id'],$row,"mysql");
}
$r = $es->searchDoc("李白 歌 水","mysql");
echo "<pre>";
print_r($r);
} else {
echo "0 结果";
}
$conn->close();
$r = $es->searchDoc("李白 歌 水","mysql");
} catch (Exception $e) {
echo $e->getMessage();
}
}else{
// $es->delIndex();
$isidnex = $es->existsIndex();
if($isidnex == false){
$es->createIndex(); //创建索引
}
//静态测试数据测试
$docs = [];
$docs[] = ['id'=>1,'title'=>'李白','content'=>'酒仙刺客','price'=>100];
$docs[] = ['id'=>2,'title'=>'孙悟空','content'=>'腾云驾雾的辜负了紫霞的刺客。','price'=>300];
$docs[] = ['id'=>3,'title'=>'胡歌','content'=>'尽职励志,不错哦。','price'=>1000000];
$docs[] = ['id'=>4,'title'=>'王者荣耀','content'=>'游戏就玩王者荣耀。','price'=>998];
$docs[] = ['id'=>5,'title'=>'鲁班','content'=>'小短腿,谁都想灭。','price'=>98];
$docs[] = ['id'=>6,'title'=>'妲己','content'=>'祸国殃民。','price'=>998];
$docs[] = ['id'=>7,'title'=>'吕布','content'=>'方天画戟,后手放大','price'=>2998];
$docs[] = ['id'=>8,'title'=>'水晶','content'=>'保护我方水晶,进攻地方水晶。','price'=>19999];
foreach ($docs as $k => $v) {
$es->addDoc($v['id'],$v); //添加文档
};
$r = $es->searchDoc("李白 歌 水");
echo "<pre>";
print_r($r);
}
The test data shows: