1.啓動xunsearchphp
/usr/local/xunsearch/bin/xs-ctl.sh start
2.建立項目配置html
官方的配置教程:http://www.xunsearch.com/doc/php/guide/ini.firstmysql
官方的配置輔助工具:http://www.xunsearch.com/tools/iniconfigsql
project.name = blog server.index = 8383 server.search = 8384 [aid] type = id [title] type = title [content] type = body
配置的幾點說明:數據庫
(1).配置內容存放在 /xunsearch/sdk/php/app/blog.ini中服務器
(2).配置的項目名爲blogapp
(3).aid字段是主鍵、title字段是個人文章標題、content字段是個人文章內容,字段數可多可少,但必需要有個主鍵字段ide
3.創建索引,這部分是用xunsearch自帶的工具爲原有的數據建立索引,若是原來沒有數據,建立索引也沒多少意義工具
執行建立索引命令格式:post
util/Indexer.php --rebuild --source=mysql://你的數據庫用戶名:你的數據庫密碼@你的數據庫IP/你的數據庫名 --sql="你要執行的SQL語句" --filter=debug --project=你的項目名 >日誌文件名
切換到sdk目錄
cd /usr/local/xunsearch/sdk/php
咱們來爲咱們的例子建立索引
util/Indexer.php --rebuild --source=mysql://root:123456@127.0.0.1/blog --sql="SELECT aid,title,content FROM article" --filter=debug --project=blog >log.txt
說明:我是在本機裝的,用的是root用戶,密碼123456,blog數據庫,article數據表,日誌寫到當前目錄/usr/local/xunsearch/sdk/php下的log.txt文件內
4.測試搜索
數據庫blog中的article表已經有3條數據
HTML的搜索代碼:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/html"> <head lang="en"> <meta charset="utf-8"> <title>搜索</title> </head> <body> <h3>全文搜索在php程序中應用</h3> <form action="search.php" method="post"> 輸入搜索的關鍵詞: <input type="text" name="keyword" /> <input type="submit" value="搜索" /> </form> <hr /> </body> </html>
search.php代碼
<?php /** * Created by me * User: 09 * Date: 2017/8/29 * Time: 16:23 */ #引入接口文件 require '/usr/local/xunsearch/sdk/php/lib/XS.php'; // 引入 xunsearch sdk if($_POST['keyword'] != ''){ $keyword = trim($_POST['keyword']); // 接收關鍵詞 $xs = new XS('blog'); // blog爲項目名稱,配置文件是:$sdk/app/blog.ini $search = $xs->search; // 獲取搜索對象 $search->setQuery($keyword); // 加入搜索關鍵詞 $docs = $search->search(); // 搜索 var_dump($docs); echo "<table border='1' cellspacing='0'><tr><th>標題</th></tr>"; foreach ($docs as $doc) { $subject = $search->highlight($doc->title); // 高亮處理標題 echo "<tr><td>".$subject."</td></tr>"; } echo "</table>"; }
遇到的問題:
1.第一步啓動xunsearch必定要作
2.cd 到/usr/local/xunsearch/sdk/php 就能夠了,若是長度到/usr/local/xunsearch/sdk/php/util 目錄,直接使用Indexer.php --rebuild --source=mysql....... 會出現 Indexer.php: command not found
3.注意創建索引的命令格式和寫法,我這裏使用localhost會出現 PHP Warning: mysqli::__construct(): (HY000/2002): No such file or directory in /data/tool/sdk/php/util/XSDataSource.class.php on line 627 ,因此改爲127.0.0.1或你的服務器IP