Elasticsearch 7.15 使用 php 8.0 版本。在 localhost 中映射 Elasticsearch 7.15 中的数据库表
<?php
require 'includes/connection.php';
require 'vendor/autoload.php';
class SearchElastic {
private $elasticclient = null;
public function __construct(){
$db = new Connection();
$this->con = $db->connect();
//echo "<pre>";print_r($this->con); //die;
$hosts = [
'http://localhost:9200' // SSL to localhost
];
$this->elasticclient = Elasticsearch\ClientBuilder::create()->setHosts($hosts)->build();
}
public function Mapping(){
$params = ['index' => 'employees'];
$response = $this->elasticclient->indices()->delete($params);
$params = [
'index' => 'employees',
'body' => [
'mappings' => [
'properties' => [
'code' => [
'type' => 'integer'
],
'name' => [
'type' => 'text'
],
'created_at' => [
'type' => 'text'
],
'last_updated' => [
'type' => 'text'
],
'rank' => [
'type' => 'integer'
],
]
]
]
];
//echo "<pre>"; print_r($params); //die;
$this->elasticclient->indices()->create($params);
}
public function Search($query){
$client = $this->elasticclient;
$result = array();
$i = 0;
$params = [
'index' => 'employees',
'type' => '_doc',
'body' => [
'query' => [
'match' => ['name' => $query],
],
'size' => 9,
'sort' => [
['rank' => 'desc'],
],
],
];
$query = $client->search($params);
$hits = sizeof($query['hits']['hits']);
$hit = $query['hits']['hits'];
$result['searchfound'] = $hits;
while ($i < $hits) {
$result['result'][$i] = $query['hits']['hits'][$i]['_source'];
$i++;
}
return $result;
}
public function InsertData(){
$this->Mapping();
$client = $this->elasticclient;
$stmt = "SELECT * FROM `table_name` limit 1";
$result = $this->con->query($stmt);
$params = null;
while ($row = $result->fetch_assoc()){
$params['body'][] = array(
'index' => array(
'_index' => 'employees',
'_type' => '_doc',
'_id' => $row['id'],
) ,
);
$params['body'][] = [
'id' => $row['id'],
'name' => $row['name'],
'created_at' => $row['created_at'],
'last_updated' => $row['last_updated'],
'rank' => $row['rank'],
];
}
$responses = $client->bulk($params);
//echo "<pre>"; print_r($responses); die;
return true;
}
public function UpdateData(){
$client = $this->elasticclient;
$stmt = "SELECT * FROM `table_name` limit 1, 1000";
$result = $this->con->query($stmt);
$params = null;
while ($row = $result->fetch_assoc()){
$params['body'][] = array(
'index' => array(
'_index' => 'employees',
'_type' => 'rules_employee',
'_type' => '_doc',
'_id' => $row['id'],
) ,
);
$params['body'][] = [
'id' => $row['id'],
'name' => $row['name'],
'created_at' => $row['created_at'],
'last_updated' => $row['last_updated'],
'rank' => $row['rank'],
];
}
$responses = $client->bulk($params);
//echo "<pre>"; print_r($responses); die;
return true;
}
}
?>