安装Elasticsearch
1.首先要有JDK环境,确保JDK8及以上版本
1.1:需要注册账号下载,可以自己注册,也可以网上搜账号
https://www.oracle.com/java/technologies/javase-jdk11-downloads.html
1.2:配置环境变量:创建变量JAVA_HOME,值是你安装jdk的路径
然后编辑path添加变量
2:安装Elasticsearch服务,选择window。(这里我安装了6.8.8版本)
https://www.elastic.co/cn/downloads/past-releases#elasticsearch
2.1:下好后进入bin目录点击elasticsearch.bat(在window系统中不要关闭)
2.2:访问http://localhost:9200/,Elasticsearch服务安装完成。
详细配置可在官方文档查看。
https://www.elastic.co/guide/en/elasticsearch/reference/6.8/getting-started.html
elasticsearch-php安装使用
1:Elasticsearch-php 的安装需要满足以下 4 个需求:
- PHP 7.0.0 或更高版本
- Composer
- ext-curl:PHP 的 Libcurl 扩展
- 原生 JSON 扩展 (ext-json) 1.3.7或更高版本
1.1:在cd到你项目下,
更换composer镜像地址,则执行:
composer -g config repo.packagist composer https://packagist.phpcomposer.com
执行以下命令,进行安装
composer require elasticsearch/elasticsearch
Elasticsearch-php安装完成,会在当前目录生成一下目录和文件:composer.json,composer.lock,vendor/
使用脚本示例
<?php
require 'vendor/autoload.php';
$client = new Elasticsearch\Client();
2:案例(mysql)
2.1:创建数据库(elastic)和表(articles)数据测试:
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使用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);
}
测试数据显示: