如果你正在尋找快速、強大的搜索功能,Elasticsearch 是合乎邏輯的選擇, 這種可擴展的搜索引擎可以執行快速、高效的全文搜索和其他復雜查詢, 你可以使用 PHP 創建一個簡單的搜索引擎來演示 Elasticsearch 的功能, 在本教程中,我們將通過使用 Elasticsearch 構建一個簡單的搜索引擎,向你展示如何使用 PHP 創建和索引檔案,
在今天的練習中,我們將使用如下的配置:

安裝
Elasticsearch
你需要按照文章 “如何在 Linux,MacOS 及 Windows 上進行安裝 Elasticsearch” 來按照好 Elasticsearch,由于我們的 Elasticsearch 需要被另外一個機器所訪問,我們修改 Elasticsearch 的配置如下:
config/elasticsearch.yml
network.host: 0.0.0.0
discovery.type: single-node
Kibana
我們需要按照文章 “Kibana:如何在 Linux,MacOS 及 Windows上安裝 Elastic 堆疊中的 Kibana” 來安裝 Kibana,
安裝完畢 Kibana 后,我們可以在 MacOS 機器上使用瀏覽器啟動 Kibana:

Apache
我們可以參考我之前的文章 “Logstash:如何使用 Elasticsearch,Logstash 和 Kibana 管理 Apache 日志” 來安裝 Apache,這里就不再累述了,
我們可以通過如下的命令來查看 Apache 服務的運行狀態:
service apache2 status
$ service apache2 status
● apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor prese>
Active: active (running) since Thu 2021-08-19 15:20:57 CST; 18s ago
Docs: https://httpd.apache.org/docs/2.4/
Process: 10214 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/S>
Main PID: 10233 (apache2)
Tasks: 55 (limit: 18982)
Memory: 7.4M
CGroup: /system.slice/apache2.service
├─10233 /usr/sbin/apache2 -k start
├─10234 /usr/sbin/apache2 -k start
└─10235 /usr/sbin/apache2 -k start
PHP
我們在 Ubuntu 機器的 terminal 中打入如下的命令來安裝 PHP:
sudo apt install php7.4-cli
我們可以通過如下的命令來查看 PHP 的版本:
$ php -v
PHP 7.4.3 (cli) (built: Jul 5 2021 15:13:35) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies
為了能夠使得 PHP 在 Apache 里運行,你需要安裝如下的包:
sudo apt-get install libapache2-mod-php7.4
否則我們的 php 腳本將不被執行,只會顯示 php 腳本本身,
安裝完畢后,你需要使用如下的命令啟動并且重新運行 Apache:
sudo a2enmod php7.4
sudo service apache2 start
為了能夠使得 Elasticsearch 的模塊能正常運行,我們需要按照如下的一個包:
sudo apt-get install php-curl
否則在下面的如下命令中:
$client = ClientBuilder::create()->build();
我們將會得到一個如下的一個例外:
Elasticsearch-PHP needs curl or custom http handler
為 Elasticsearch PHP 搜索引擎設定檔案夾
一旦我們確認所有系統要求都已到位,我們就可以為 Elasticsearch PHP 搜索引擎設定檔案夾,
首先,在終端視窗中使用 cd 命令導航到包含客戶端 vendor 庫的目錄, 你也可以只記下 vendor 庫的相對路徑,以便將其包含在腳本中,
接下來,創建一個新目錄,其中將包含你的 PHP 腳本和供應商目錄, 在 Linux 終端視窗中,使用以下命令:
cd /var/www/html
sudo mkdir elastic-php
sudo chown -R $USER:$USER /var/www/html/elastic-php
sudo chmod -R 755 /var/www
cd elastic-php
如果您在創建此目錄時遇到任何問題,可能是由于父目錄的權限問題,
我們接下來參照 Elastic 官方檔案,你也可以參考鏈接,我們首先進入到 elastic-php 檔案夾,并創建如下的一個檔案:
sudo vi composer.json
我們把如下的內容輸入進去:
composer.json
{
"require": {
"elasticsearch/elasticsearch": "~7.0"
}
}
我們接著打入如下的命令:
sudo curl -s http://getcomposer.org/installer | php
liuxg@liuxgu:/var/www/html/elastic-php$ sudo curl -s http://getcomposer.org/installer | php
All settings correct for using Composer
Downloading...
Composer (version 2.1.5) successfully installed to: /var/www/html/elastic-php/composer.phar
Use it: php composer.phar
經過上面的步驟,我們可以看到如下的檔案:
$ pwd
/var/www/html/elastic-php
liuxg@liuxgu:/var/www/html/elastic-php$ ls
composer.json composer.phar
我們接著使用如下的命令來安裝 Elasticsearch PHP:
php composer.phar install
liuxg@liuxgu:/var/www/html/elastic-php$ php composer.phar install
Composer is operating significantly slower than normal because you do not have the PHP curl extension enabled.
No composer.lock file present. Updating dependencies to latest instead of installing from lock file. See https://getcomposer.org/install for more information.
Loading composer repositories with package information
Updating dependencies
Lock file operations: 5 installs, 0 updates, 0 removals
- Locking elasticsearch/elasticsearch (v7.14.0)
- Locking ezimuel/guzzlestreams (3.0.1)
- Locking ezimuel/ringphp (1.1.2)
- Locking psr/log (1.1.4)
- Locking react/promise (v2.8.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
- Downloading psr/log (1.1.4)
- Downloading react/promise (v2.8.0)
- Downloading ezimuel/guzzlestreams (3.0.1)
- Downloading ezimuel/ringphp (1.1.2)
- Downloading elasticsearch/elasticsearch (v7.14.0)
- Installing psr/log (1.1.4): Extracting archive
- Installing react/promise (v2.8.0): Extracting archive
- Installing ezimuel/guzzlestreams (3.0.1): Extracting archive
- Installing ezimuel/ringphp (1.1.2): Extracting archive
- Installing elasticsearch/elasticsearch (v7.14.0): Extracting archive
3 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
經過上面的安裝后,我們可以看到如下的檔案:
$ pwd
/var/www/html/elastic-php
liuxg@liuxgu:/var/www/html/elastic-php$ ls
composer.json composer.lock composer.phar vendor
Elasticsearch 的 PHP 客戶端庫包含在 Composer 創建的 vendor 檔案夾中,
我們接下來創建兩個檔案:
- index.php
- add.php
我們將創建的搜索引擎使用兩個 PHP 腳本:一個使用 HTML 來創建搜索查詢,另一個將 HTML 資料放入 Elasticsearch 索引中, 默認情況下將在沒有指定路徑的情況下運行的主要 PHP 腳本將是 index 腳本:
sudo touch index.php
sudo touch add.php
經過上面的命令后,我們的檔案如下:
$ pwd
/var/www/html/elastic-php
liuxg@liuxgu:/var/www/html/elastic-php$ ls
add.php composer.json composer.lock composer.phar index.php vendor
我可以使用自己喜歡的編輯器來辯解 index.php 檔案,
為了能夠使得 Apache 能夠顯示我們剛才創建的 index.php 檔案,我們按照如下的步驟來操作:
創建一個叫做 test.dev 的檔案:
/etc/apache2/sites-available/test.dev.conf
<VirtualHost *:80>
ServerName test.dev
ServerAdmin admini@test.dev
DocumentRoot /var/www/html/elastic-php
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
創建完畢后,我們使用如下的命令來啟動:
sudo a2dissite 000-default.conf
sudo a2ensite test.dev.conf
systemctl reload apache2
經過上面的命令,我們可以查如下的目錄:
$ pwd
/etc/apache2/sites-enabled
liuxg@liuxgu:/etc/apache2/sites-enabled$ ls
test.dev.conf
從上面我們可以看出來 test.dev.conf 目前是唯一可見的網站,
我們接下來修改 add.php 檔案的內容:
/var/www/html/elastic-php/add.php
<?php
require 'vendor/autoload.php'; //(1)
use Elasticsearch\ClientBuilder;
$hosts = [
'192.168.0.3:9200' // IP + Port
];
try {
$client = ClientBuilder::create() // (2) Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build(); // (3) Build the client object
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage() .'<br>';
}
if(!empty($_POST)){ // (4)
if(isset($_POST['name'],$_POST['gender'], $_POST['age'],
$_POST['complexion'],
$_POST['attributes'])){
$name = $_POST['name'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$complexion = $_POST['complexion'];
$attributes = explode(',', $_POST['attributes']); // (5)
// (6)
$indexed = $client->index([
'index' => 'children',
'type' => 'child',
'body' => [
'name' => $name,
'gender' => $gender,
'age' => $age,
'complexion' => $complexion,
'attributes' => $attributes
],
]);
}
}
?>
這段代碼有很多內容,所以讓我們看幾個關鍵部分,以便更好地理解它:
- 在代碼的頂部,注意 Composer 的 autoload.php 是必需的, 這會加載它下載的任何庫中的所有類,
- 接下來,我們實體化一個新的 ClientBuilder,并構建客戶端物件,
- 然后我們檢查以確保 $_POST “superglobal” 變數在提交表單時確實包含值,
- explode() 函式用于將字串拆分為陣列,
- 然后我們創建關聯陣列并將其傳遞給 Elasticsearch 客戶端進行索引,一個新的 child 檔案被索引到代碼中指定的 children 索引中,
在接下來,我們來撰寫 index.php 的代碼:
/var/www/html/elastic-php/index.php
<?php
require 'vendor/autoload.php'; // (1)
use Elasticsearch\ClientBuilder;
$hosts = [
'192.168.0.3:9200' // IP + Port
];
try {
$client = ClientBuilder::create() // (2) Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build(); // (3) Build the client object
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage() .'<br>';
}
echo "ES client has been created. <br>";
$query = $_GET['q'];
echo "You are going to search for: " .$query ."<br>";
if(isset($_GET['q'])) { // (4)
$q = $_GET['q'];
$query = $client->search([
'body' => [
'query' => [ // (5)
'bool' => [
'must' => [
'match' => ['name' => $q]
]
]
]
]
]);
if($query['hits']['total'] >=1 ) { // (6)
$results = $query['hits']['hits'];
print_r($results);
}
}
?>
就像我們在前面的代碼示例中所做的那樣,讓我們仔細看看這個腳本,以便更好地理解發生了什么:
- 首先,composer 的 autoload.php 加載它下載的任何庫中的所有類,
- 接下來,我們實體化一個新的 ClientBuilder,并構建客戶端物件,
- 然后我們檢查是否在 “superglobals” $_GET 中設定了值,
- 這個多查詢字串告訴我們查詢應該匹配我們在 $q 變數中傳遞的引數,
- “hits”的 “total” 只是告訴我們有多少結果,
我們接下來在 /var/www/html/elastic-php 位置分別創建兩個子目錄: add 及 search,在 add 子目錄下創建如下的一個 index.html 檔案:
/var/www/html/elastic-php/add/index.html
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<title>Add Child Details</title>
</head>
<body>
<form action="../add.php" method="post" autocomplete="off">
<div>
<label>
Name
<input type="text" name="name">
</label>
<br>
<label>
Gender
<input type="text" name="gender">
</label>
<br>
<label>
Age
<input type="text" name="age" placeholder="number only">
</label>
<br>
<label>
Complexion
<input type="text" name="complexion">
</label>
<br>
<label>
The Attributes
<textarea type="text" name="attributes" rows="4" placeholder="comma, separated attributes" ></textarea>
</label>
<input type="submit" value="Add">
</div>
</form>
</body>
</html>
這是一個非常之簡單的 HTML 檔案,我們在瀏覽器中運行它:

點擊上面的 Add 按鈕,這樣一個新的檔案就在 Elasticsearch 中生成了,
我們在 Kibana 中來進行查看:

從上面我們可以看出來,我們的檔案已經被寫入到 Elasticsearch 中了,
接下來,我們通過網頁對寫入的檔案進行搜索,我們在 search 子目錄下創建如下的一個 index.html 檔案:
/var/www/html/elastic-php/search/index.html
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<title>Search Elasticsearch</title>
</head>
<body>
<form action="../index.php" method="get" autocomplete="off">
<label>
Search for Something
<input type="text" name="q">
</label>
<input type="submit" value="search">
</form>
<div class="res">
<a href="#id">Name</a>
</div>
<div>Attributes</div>
</body>
</html>
我們在瀏覽器中顯示這個頁面:

同樣這也是一個非常簡單的 HTML 頁面,我們在上面的輸入框中輸入 liuxg,并點擊 search 按鈕:
我們在頁面中看到被搜索的檔案,
參考
【1】https://linuxhint.com/install_apache_web_server_ubuntu/
【2】 https://github.com/elastic/elasticsearch-php
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/295357.html
標籤:其他
