成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

php + MongoDB + Sphinx 實現(xiàn)全文檢索

Simon_Zhou / 3021人閱讀

摘要:此文成于年月現(xiàn)狀目前的穩(wěn)定版本為目前對英文等字母語言采用空格分詞故其對中文分詞支持不好目前官方中文分詞方案僅支持按單字分詞在基礎上目前國內(nèi)有兩個中文分詞解決方案一個是一個是沒有官網(wǎng)文檔較少可查到的最新版本可支持官方還在維護但貌似不打

NOTE : 此文成于 2017 年 3 月.
現(xiàn)狀:

Sphinx 目前的穩(wěn)定版本為 2.2.11.
Sphinx 目前對英文等字母語言采用空格分詞,故其對中文分詞支持不好,目前官方中文分詞方案僅支持按單字分詞.
在 Sphinx 基礎上,目前國內(nèi)有兩個中文分詞解決方案,一個是 sphinx-for-chinese, 一個是 coreseek.
sphinx-for-chinese 沒有官網(wǎng),文檔較少,可查到的最新版本可支持 sphinx 1.10 .
coreseek 官方還在維護,但貌似不打算將最新版作為開源方案釋出了.
coreseek 最后的開源穩(wěn)定版本為 3.2.14, 更新時間為2010年中, 基于 sphinx 0.9.9, 不支持string類型的屬性.
coreseek 最后的開源beta版本為 4.1, 更新時間為2011年底, 基于 sphinx 2.0.2, 已可支持string類型的屬性.
相比而言, coreseek 文檔較多,網(wǎng)上用的也更為廣泛,因此使用 coreseek 方案.
目前暫時用了 coreseek 3.2.14 穩(wěn)定版,在后續(xù)了解中,發(fā)現(xiàn)使用 4.1 beta版更為合適.后續(xù)需更換.
注: 如果要使用 coreseek, 要注意其 sphinx 版本.看文檔時,不要去看 sphinx 最新文檔,而要看對應版本的.

搭建:

基于 CentOS 6.5 . 安裝 coreseek:
Coreseek 官網(wǎng)下載地址已失效 (-_- !!!), 需要自己在網(wǎng)上找一個.
Coreseek 官方給出的 安裝文檔 已非常詳實.
因為我們不是為了替換 mysql 的全文檢索,因此不需要安裝 mysql 的 sphinx 插件.

安裝 php 的 sphinx 擴展:
Sphinx 官方文檔中直接包含了 php 調(diào)用 sphinx 的文檔,因此還是相當方便的.
擴展安裝方法,當時沒記錄下來,也不難,網(wǎng)上一大堆.這里就不展開了...
擴展需要編譯兩個 so 文件 (當然路徑不一定是我這個路徑.):

/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/sphinx.so
/usr/local/lib/libsphinxclient-0.0.1.so

需要在 php.ini 中增加擴展:

extension=sphinx.so
將 MongoDB 作為數(shù)據(jù)源:

sphinx 最常見搭配是 mysql + php. 非mysql數(shù)據(jù)源需要解決數(shù)據(jù)導入問題.
用 Sphinx 全文索引 MongoDB 主要有兩個問題需要解決:
一是導入數(shù)據(jù)到 sphinx 索引, 二是 mongo objectId 到 sphinx document id 的映射.

第 一個問題還算好解決,因為除了 mysql, sphinx 還支持 xml 和 python 數(shù)據(jù)源.但這里還是建議用 mysql 作為 mongo 數(shù)據(jù)的中轉(zhuǎn),因為 xml 數(shù)據(jù)源不支持步進取數(shù)據(jù),性能會是個大問題. python 數(shù)據(jù)源需要額外增加編譯項目,搞了半天沒有編譯過去,又查不到幾篇文檔,就放棄了.

第二個問題,起因是 sphinx 有一條重要限制,就是其索引的每條數(shù)據(jù)都需要一個 "唯一,非零,32位以下 的 整數(shù)" 作為 id. 而 mongo 的 objectId 是一個 24位16進制字符串, 這串16進制轉(zhuǎn)為10進制是一個 64-bit int 都存不下的大數(shù).
在 sphinx 1.10 后也算好解決. mongo 的 objectId 可以作為 sphinx 索引中的一個 string 類型的屬性值存起來 . 但目前 sphinx 的最新版本,官方文檔中也是寫明 string 屬性會被保存在內(nèi)存而非索引文件中,數(shù)據(jù)集較大時則需要考慮這方面的性能. 總之如果可以用 int 類型的 sphinx 屬性,就盡量不要用 string 類型的 sphinx 屬性.
在 sphinx 0.9.9 中,不支持 string 作為屬性,只能用 int, bigint, bool 等作為屬性. 而我采用的是 coreseek 3.2.14 - sphinx 0.9.9. 因此肯定需要再想辦法.

最 終的辦法是,將 24 個字母的 16 進制 objectId 分為 4 段,每段 6 個字母.每段轉(zhuǎn)換為10進制數(shù)就可以落在一個 32-bit uint 范圍內(nèi)了.這4個 objectId 的片段作為屬性被 sphinx 索引,拿到查詢結(jié)果后,再將其還原為 mongo 的 objectId. Sphinx 的 document id 則采用無具體意義的自增主鍵.

將全文檢索作為系統(tǒng)服務:

將全文檢索服務獨立出來,作為多帶帶項目,向外暴露ip或端口來提供服務.需實現(xiàn)以下功能:

1.?新增或修改索引,由單一文件(下稱 driver file)驅(qū)動如下功能:

?? * data source -> mysql : 由數(shù)據(jù)源(mongo)向mysql中轉(zhuǎn)數(shù)據(jù)

?? * generate sphinx index conf : 生成sphinx索引配置文件

?? * mysql -> sphinx (create index) : 由mysql數(shù)據(jù)及sphinx配置文件生成索引

單一 bash 腳本實現(xiàn)更新索引,重建索引,以便 crontab 引用

查詢時自動返回 driver file 中描述的字段,并包括數(shù)據(jù)在mongo中的庫名及表名,以便反向查詢

難點及核心在于 driver file 的策略.

Plan A:

mongo -> mysql -> sphinx , 三者間有兩重轉(zhuǎn)換:

字段類型轉(zhuǎn)換

字段值轉(zhuǎn)移

因此第一想法是將字段含義抽象出來,溝通三者.
字段抽象類提供接口,分別返回 mongo, mysql, sphinx 對應字段類型,并編寫接口將字段值在三者間映射.
初步定下三種字段類型:

attr_object_id : 用以映射 mongo 中的 ObjectId
attr_field : 用以將 string 類型字段映射為 sphinx 全文檢索項
attr_int : 用以將 int 類型字段映射為 sphinx 屬性 (可用作排序,過濾,分組)

driver file 則選取 json, xml 等通用數(shù)據(jù)格式 (最終選擇了 json).
因為一個index的數(shù)據(jù)源有可能有多個,因此要求 driver file 中可配置多個數(shù)據(jù)源 (json 數(shù)組)
如下為一個具體索引對應的 driver file:

{
  "name": "example_index",
  "source": [
    {
      "database": "db_name",
      "table": "table_name",
      "attrs": [
          { "mongo": "text1", "type": "field" },
          { "mongo": "text2", "type": "field" },
          { "mongo": "_id", "type": "objectId" },
          { "mongo": "type", "type": "int" },
          { "mongo": "someId", "type": "int" },
          { "mongo": "createTime", "type": "int" },
          { "mongo": "status", "type": "int" }
        ]
    }
  ]
}

為每個索引配置一個此格式的json文件,解析所有json文件,則可完成 mongo -> mysql -> sphinx 的流程.

已編碼完成字段抽象, mongo -> mysql 部分.
編寫過程及后續(xù)思考中,發(fā)現(xiàn)這種抽象方式有如下缺點:

編碼復雜: int 類型的映射規(guī)則尚簡單,object_id這樣的字段需要將mongo中的一個字段映射為mysql中的四個字段,則要求統(tǒng)一將字段抽象接口都定義為一對多的映射,復雜度增加.以字段為基本單元,編碼需要多次遍歷,多層遍歷,復雜度增加.

字段接口的共同屬性不足: 除了上述一個一對多字段將所有字段都抽象為一對多外,當操作最新的mongo維權(quán)表時意識到,即使只限定將一個mongo表映射到一個sphinx索引中,也會遇到全文索引字段被保存在其他表中的情況.比如維權(quán)表中的tag是以id數(shù)組的形式存儲的,因此在轉(zhuǎn)儲數(shù)據(jù)時需要查詢tag表.這種行為只能多帶帶為字段抽象接口編寫一個實現(xiàn)類,而這個實現(xiàn)類也只能用于tag這一個字段而已.這種抽象方式會導致具體實現(xiàn)類過多,且關(guān)聯(lián)不大.

只能支持 mongo -> mysql -> sphinx 這樣的數(shù)據(jù)源配置.如果有其他數(shù)據(jù)源,則不能采用這種抽象方式.

基于以上缺陷,決定放棄此方案(在此方案上已耗費了三天的工作量 T_T)

Plan B:

再次思考應用場景,可將模型簡化:

規(guī)劃功能中的第三點, "查詢時自動返回 driver file 中描述的字段,并包括數(shù)據(jù)在mongo中的庫名及表名,以便反向查詢",是希望做到對調(diào)用者完全透明:
調(diào)用者不需要知道具體索引了哪些字段,就可以根據(jù)查詢結(jié)果在mongo數(shù)據(jù)庫中檢索到相應數(shù)據(jù). 但為了實現(xiàn)完全黑箱化,需要的工作量太大,比如 driver file 內(nèi)需要添加描述搜索返回數(shù)據(jù)的接口,以及反向映射某些字段的接口(比如mongo的objectId).
將此功能簡化為:
1.?根據(jù) driver file 為每個索引生成一個靜態(tài)的幫助頁面(manual),在此頁面中列出索引字段.這樣功能實現(xiàn)尚可接受,而 driver file 將可減少很多職能: 只關(guān)注索引建立,不關(guān)注索引查詢.

編寫索引查詢接口,定義一個字段轉(zhuǎn)換的interface,用于將查詢出的 sphinx 屬性反向映射到希望得到的數(shù)據(jù).

既然不需要為每個字段建立反指向數(shù)據(jù)源的映射,就更沒有必要以字段作為抽象依據(jù). driver file 只關(guān)注索引建立,因此可以將建立索引的各個步驟作為抽象依據(jù).
以步驟作為抽象依據(jù),相比于以字段作為抽象依據(jù),
缺點是:

-?driver file 將不再是靜態(tài)的, driver file 內(nèi)必須包含代碼羅輯,且每增加一個 driver file (對應一個索引),都要寫新的代碼羅輯;

因為索引的維護和索引的查詢被分開,則在一個索引有屬性改動時,需要更改兩個文件: driver file 和 查詢字段映射規(guī)則;

-?抽象程度較低,各 driver file 之間可公用的部分較少.
優(yōu)點是:
-?實現(xiàn)簡單(do not over design);
-?可以靈活適配其他類型數(shù)據(jù)源;

為了可以支持一個 sphinx 索引的數(shù)據(jù)來自 mongo 的多個庫和多個表的情況, Plan A 引入了json數(shù)組.但其實可以將 index 與數(shù)據(jù)庫表 一對多 的關(guān)系,放在 mongo -> mysql 數(shù)據(jù)中轉(zhuǎn)時實現(xiàn),sphinx 永遠只索引來自同一張 mysql 數(shù)據(jù)庫表的數(shù)據(jù).即由 "mongo 多對一 mysql + sphinx" 改為 "mongo 多對一 mysql, mysql 一對一 sphinx". 這種做法下,將 mongo -> mysql 的實現(xiàn)方式自由度放的大些,其他步驟就可以統(tǒng)一實現(xiàn)了.

該方案將整個項目分為不相關(guān)的兩個部分:
一部分是由bash腳本驅(qū)動的索引操作 (重建 sphinx conf 文件; 更新索引; 導入數(shù)據(jù)等) 工具集;
一部分是由 nginx + phalcon 驅(qū)動的索引查詢 restful api 接口.

索引操作工具集:

這個方案中,所有 driver file 都繼承如下接口:

/**
 * @author lx
 * date: 2016-11-30
 * 
 * 該接口代表一個 sphinx 索引項目.用于完成以下任務:
 * data source => mysql
 * create sphinx searchd.conf
 * refresh sphinx index with searchd.conf
 * create manual (static web page) for each index
 */
interface IndexDriver {

    /**
     * 索引名稱,需在項目內(nèi)唯一.
     */
    public function getIndexName();

    /**
     * 索引字段數(shù)組: 元素為 IndexField 類型的數(shù)組.
     * @see IndexField
     */
    public function getIndexFields();

??? /** 
???? * 用于在 crontab 調(diào)度中,判斷是否要重建索引
???? * @param last_refresh_time 上一次重建索引的時間, 單位秒
???? * @return 需要重建則返回 true; 不需要重建則返回 false
???? */
??? public function shouldRefreshIndex($last_refresh_time);

    /**
     * 以步進方式獲取數(shù)據(jù), 需和 getIndexFields() 對應.
     * 數(shù)據(jù)為二維數(shù)組:
     * 第一個維度為順序數(shù)組,代表將要插入mysql的多行數(shù)據(jù);
     * 第二個維度為鍵值對數(shù)組,代表每行數(shù)據(jù)的字段及其值.
     * example:
     * array(
     *     array("id" => "1", "type" => "404", "content" => "I"m not an example"),
     *     array("id" => "2", "type" => "500", "content" => "example sucks"),
     *     array("id" => "3", "type" => "502", "content" => "what"s the point /_"),
     * )
     * 
     * @param int $offset 步進偏移量
     * @param int $limit 返回數(shù)據(jù)的最大行數(shù)
     */
    public function getValues($offset, $limit);

    /**
     * 為該索引生成相應文檔.
     */
    public function generateDocument();
}

字段以如下類表示:

/**
 * @author lx
 * date: 2016-11-30
 * 
 * 該類代表一個 sphinx 全文索引字段 或 sphinx 索引屬性.
 */
class IndexField {

    private $name;
    private $mysql_type;
    private $sphinx_type;

    /**
     * 創(chuàng)建作為 sphinx int 類型屬性的 IndexField. 該字段必須為一個正整數(shù).
     * @param string $name 字段名
     */
    public static function createIntField($name) {
        return new IndexField($name, "int", "sql_attr_uint");
    }

    /**
     * 創(chuàng)建作為 sphinx 全文索引字段的 IndexField. 該字段必須為一個字符串.
     * @param string $name 字段名
     * @param int $char_length 字段值的最大長度.
     */
    public static function createField($name, $char_length = 255) {
        return new IndexField($name, "varchar($char_length)", null);
    }

    /**
     * @param string $name 字段名
     * @param string $mysql_type 該字段在mysql下的類型
     * @param string $sphinx_type 該字段在sphinx配置文件中的類型
     */
    public function __construct($name, $mysql_type, $sphinx_type = null) {
        $this->name = $name;
        $this->mysql_type = $mysql_type;
        $this->sphinx_type = $sphinx_type;
    }

    /**
     * 獲取字段名.
     */
    public function getName() {
        return $this->name;
    }

    /**
     * 獲取該字段在 mysql 數(shù)據(jù)庫中的類型.主要用于 mysql create 語句創(chuàng)建數(shù)據(jù)表.
     * 例: 可能返回的值如下:
     * int
     * varchar(255)
     */
    public function getMysqlType() {
        return $this->mysql_type;
    }

    /**
     * 獲取該字段在 sphinx conf 文件中的類型.主要用于構(gòu)建全文索引conf文件.
     * 如果該字段為一個全文索引字段,則該函數(shù)應返回 null.
     * 例: 可能返回的值如下:
     * sql_attr_uint
     */
    public function getSphinxType() {
        return $this->sphinx_type;
    }

    /**
     * 判斷該字段是否為全文索引字段.
     * 目前的判斷依據(jù)為 sphinx_type 是否為空.
     */
    public function isSphinxField() {
        return empty($this->sphinx_type);
    }
}

將需要做索引的數(shù)據(jù)源都抽象為上述 driver file, 然后將所有 driver file 統(tǒng)一放在一個文件夾下.編寫腳本掃描該文件夾,根據(jù) driver file 列表實現(xiàn)重建sphinx索引配置文件,更新索引(全量,增量),crontab排期任務等操作. 當未來有新的數(shù)據(jù)源要建立索引,或者現(xiàn)有數(shù)據(jù)源調(diào)整時,只需要更新 driver file 即可.

可將索引相關(guān)操作分解到三個類中:
MysqlTransmitter: 用于將數(shù)據(jù)導入 mysql
SphinxConfGenerator: 用于重建 sphinx 配置文件 (只能重建,不能更新.不過開銷很小,不構(gòu)成問題)
DocumentGenerator: 用于為每個索引建立手冊頁面

然后再編寫統(tǒng)一入口腳本,調(diào)用以上工具類,接合 sphinx 的內(nèi)建工具 searchd, indexer 等,完成索引相關(guān)操作.
該部分已全部實現(xiàn),目前運行良好.

索引查詢:

上文采用 Plan B 后,需要制定一套索引屬性反向映射規(guī)則.

比如 mongo 的 ObjectId, 其在數(shù)據(jù)源導入時被拆開為4個int類型數(shù)字,現(xiàn)在要將這4個int類型拼接為可用的 ObjectId,以便進一步查詢 mongo.
比如有一個字段 code,需要在其前面補零才可與 mongo 內(nèi)的某個字段對應起來.

這是一個多對多映射問題: 將 sphinx 查詢出的多個屬性轉(zhuǎn)換為其他的多個屬性.因此定義如下接口:

/**
 * 將 sphinx 查詢到的一個或多個屬性進行轉(zhuǎn)換,并加入到查詢結(jié)果中去.
 * 被轉(zhuǎn)換的屬性將從結(jié)果集中去掉; 轉(zhuǎn)換結(jié)果將被加入到結(jié)果集中去.
 * @author lx
 */
interface FieldParser {
    /**
     * 聲明要轉(zhuǎn)換的 sphinx 屬性名稱.
     * 這些被指定的屬性的值將作為參數(shù)傳入 parseValues() 函數(shù)中.
     * @return array 屬性名稱的數(shù)組.例: array("id1", "id2", "id3)
     */
    function getRequiredKeys();

    /**
     * 將選定的屬性值進行轉(zhuǎn)換.轉(zhuǎn)換結(jié)果以鍵值對數(shù)組形式返回.
     * @param array $values 選定的屬性值,鍵值對數(shù)組.
     * @return array 屬性及其值的兼職對. 例: array("id" => "123", "id_ext" => 456)
     */
    function parseValues(array $values);
}

將該接口的具體實現(xiàn)類加入到一個數(shù)組(隊列),逐個遍歷,以對sphinx的返回結(jié)果集進行轉(zhuǎn)換.

以 mongo 的 ObjectId 為例,其具體轉(zhuǎn)換類實現(xiàn)如下:

class MongoIdParser implements FieldParser {

    private $field_name;
    private $required_fields;

    public function __construct($field_name) {
        $this->field_name = $field_name;
        $this->required_fields = array(
            $this->field_name."1", $this->field_name."2",
            $this->field_name."3", $this->field_name."4",
        );
    }

    /**
     * {@inheritDoc}
     * @see FieldParser::getFieldNames()
     */
    public function getRequiredKeys() {
        return $this->required_fields;
    }

    /**
     * {@inheritDoc}
     * @see FieldParser::parseFieldValues()
     */
    public function parseValues(array $values) {
        $mongoId = $this->buildMongoId(
            $values[$this->field_name."1"],
            $values[$this->field_name."2"],
            $values[$this->field_name."3"],
            $values[$this->field_name."4"]);
        return array($this->field_name => $mongoId);
    }

    private function buildMongoId($_id1, $_id2, $_id3, $_id4) {
        $id = $this->toHex($_id1).$this->toHex($_id2).$this->toHex($_id3).$this->toHex($_id4);
        if (strlen($id) != 24) {
            return "";
        } else {
            return $id;
        }
    }

    private function toHex($_id) {
        $hex_str = dechex($_id);
        $count = strlen($hex_str);
        if ($count < 1 || $count > 6) {
            return "";
        }
        if ($count < 6) {
            for ($i = 0; $i < 6 - $count; $i ++) {
                $hex_str = "0".$hex_str;
            }
        }
        return $hex_str;
    }
}

有了以上接口后,定義一個方便調(diào)用的查詢 sphinx 的類.

因為 sphinx 本身對php支持已經(jīng)極度友好了,其實除了上面提到的屬性值轉(zhuǎn)換功能,基本沒什么需要封裝的了.
但因為大愛流式調(diào)用,因此就把調(diào)用sphinx封裝為流式調(diào)用了.如下:

/**
 * @author lx
 * date: 2016-11-25
 * utility class to easy access sphinx search api.
 */
class EcoSearch {

    private $sphinx;
    private $query_index;

    private $field_parsers;

    /**
     * construct with sphinx searchd ip and port
     * @param string $ip  sphinx searchd ip
     * @param int $port  sphinx searchd port
     */
    public function __construct($ip, $port) {
        $this->sphinx = new SphinxClient();
        $this->sphinx->setServer($ip, $port);
        $this->sphinx->SetMatchMode(SPH_MATCH_ANY);
    }

    /**
     * construct with sphinx searchd ip and port
     * @param string $ip  sphinx searchd ip
     * @param int $port  sphinx searchd port
     */
    public static function on($ip = "127.0.0.1", $port = 9312) {
        $search = new EcoSearch($ip, $port);
        return $search;
    }

    public function setMatchAll() {
        $this->sphinx->SetMatchMode(SPH_MATCH_ALL);
        return $this;
    }

    public function setMatchAny() {
        $this->sphinx->SetMatchMode(SPH_MATCH_ANY);
        return $this;
    }

    public function setSortBy($attr, $asc = true) {
        if (!empty($attr) && is_string($attr)) {
            $mode = $asc ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC;
            $this->sphinx->SetSortMode($mode, $attr);
        }
        return $this;
    }

    public function setMongoIdName($mongo_id_name) {
        return $this->addFieldParser(new MongoIdParser($mongo_id_name));
    }

    public function addQueryIndex($index) {
        if (!empty(trim($index))) {
            $this->query_index = $this->query_index." ".$index;
        }
        return $this;
    }

    public function addFilter($attr, $values, $exclude = false) {
        $this->sphinx->SetFilter($attr, $values, $exclude);
        return $this;
    }

    public function addFilterRange($attr, $min, $max, $exclude = false) {
        $this->sphinx->SetFilterRange($attr, $min, $max, $exclude);
        return $this;
    }

    public function setLimits($offset, $limit) {
        $this->sphinx->SetLimits($offset, $limit);
        return $this;
    }

    public function addFieldParser($field_parser) {
        if ($field_parser instanceof FieldParser) {
            if (!$this->field_parsers) {
                $this->field_parsers = array();
            }
            $this->field_parsers[] = $field_parser;
        }
        return $this;
    }

    public function query($str) {
        if (empty(trim($this->query_index))) {
            $this->query_index = "*";
        }
        Logger::dd("search [$str] from index {$this->query_index}");
        $result_set = $this->sphinx->Query($str, $this->query_index);
        $error = $this->sphinx->GetLastError();
        if (!$error) {
            Logger::ww("search [$str] from index {$this->query_index}, last error: $error");
        }
        $ret = array();
        if (is_array($result_set) && isset($result_set["matches"])) {
            foreach ($result_set["matches"] as $result) {
                $ret_values = array();
                $values = $result["attrs"];
                foreach ($this->field_parsers as $parser) {
                    $parsed_values = $this->getParsedValues($parser, $values);
                    $ret_values = array_merge($ret_values, $parsed_values);
                }
                $ret_values = array_merge($ret_values, $values);
                $ret[] = $ret_values;
            }
        } else {
            //echo "sphinx query fail: ".$this->sphinx->GetLastError()."
";
        }
        return $ret;
    }

    private function getParsedValues($parser, &$values) {
        $ret = null;
        $required_keys = $parser->getRequiredKeys($values);
        if (!empty($required_keys)) {
            $required_values = array();
            foreach ($required_keys as $key) {
                // get required values
                $required_values[$key] = $values[$key];
                // abondon the already parsed keys
                unset($values[$key]);
            }
            if (!empty($required_values)) {
                $ret = $parser->parseValues($required_values);
            }
        }
        return $ret;
    }
}

一個全文檢索調(diào)用的形式大體如下:

        $offset = ($_POST["page"] - 1) * $_POST["pageSize"];
        $limit = $_POST["pageSize"];
        $search_result = EcoSearch::on()
            ->addQueryIndex("index_name")
            ->setMatchAll()
            ->setSortBy("createTime", false)
            ->setLimits($offset, $limit)
            ->setMongoIdName("_id")
            ->query($search);

        if (empty($search_result)) {
            // response "未搜索到相關(guān)結(jié)果";
        } else {
            $result = array();
            foreach ($search_result as $r) {
                $result[] = query_mongo_by_id(new MongoDBBSONObjectID($r["_id"]));
            }
            // response result set
        }

因為 sphinx 提供的 weight, group, 并行查詢(AddQuery) 等,目前項目中并沒有使用場景,因此這個查詢輔助類就已經(jīng)夠用了.

后記:

按以上思路,整個項目的大體框架已搭建完成,后續(xù)還需要增加對各個接口類的實現(xiàn)等工作.
只寫了大體思路,隨想隨寫(一大半是在出去浪的飛機上寫的...),肯定比較亂.聊做筆記,各位看客見諒~.

參考:

Sphinx 官網(wǎng)
Coreseek 官網(wǎng)


后后記:

本來領(lǐng)導讓搭建 sphinx 時說只支持非實時索引即可, 后來又整幺蛾子, 讓做實時索引.
實時索引就得讓后臺在數(shù)據(jù)入庫時附帶著在 sphinx 這也插入一份, 但領(lǐng)導又要求不能影響主框架, 讓我想辦法異步實現(xiàn)自己找到差異數(shù)據(jù)往 sphinx 里面插.
但但但... php 不支持異步啊... 殘念...

幾經(jīng)掙扎后, 我決定整體放棄這套 php 代碼, 轉(zhuǎn)而用 python 按上面思路重新寫了一遍, 對下面幾個方面進行了改進:

Mongo ObjectId 的拆分不再是按6位分割來拆, 而是按照其定義拆為 4 個有意義的整型值.

實現(xiàn)了 python 流式生成/讀取 xml 文檔, 不再需要 mysql 做中轉(zhuǎn).

改進流程, 讓其自動化程度更高.

引入增量索引機制, 避免單次索引重建耗時過長.

引入 SphinxQL 機制來支持實時索引.

用 flask 搭建了一個 api 服務器, 以實現(xiàn)和主框架解偶.

有空時再寫寫這個 python 框架吧.

另: 后來又接觸并搭建了 elasticsearch, 感覺現(xiàn)在用 sphinx 畢竟是少了, 畢竟其中文分詞器居然還不是外掛插件就可以的, 居然還要改源碼... 但兩個搜索框架都用了, 會發(fā)現(xiàn) sphinx 占用資源比 elasticsearch 少的多. 呃... 起碼在我這個規(guī)模上吧.

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/19237.html

相關(guān)文章

  • php + MongoDB + Sphinx 實現(xiàn)全文檢索

    摘要:此文成于年月現(xiàn)狀目前的穩(wěn)定版本為目前對英文等字母語言采用空格分詞故其對中文分詞支持不好目前官方中文分詞方案僅支持按單字分詞在基礎上目前國內(nèi)有兩個中文分詞解決方案一個是一個是沒有官網(wǎng)文檔較少可查到的最新版本可支持官方還在維護但貌似不打 NOTE : 此文成于 2017 年 3 月. 現(xiàn)狀: Sphinx 目前的穩(wěn)定版本為 2.2.11.Sphinx 目前對英文等字母語言采用空格分詞,故...

    dockerclub 評論0 收藏0
  • App后臺api開發(fā)前的準備

    摘要:負責從拉取數(shù)據(jù)源,把數(shù)據(jù)源分詞,建立索引搜索模塊工作流程如下模塊從中拉取數(shù)據(jù)模塊用經(jīng)過中文分詞后的數(shù)據(jù)建立索引客戶端向模塊發(fā)起搜索請求模塊查找索引中的數(shù)據(jù)模塊得到索引中符合要求的數(shù)據(jù)的等數(shù)據(jù)把數(shù)據(jù)返回給客戶端 (整理自《App后臺開發(fā)運維和架構(gòu)實踐》 作者:曾健生) 一、從業(yè)務邏輯中提煉API接口 此過程可分為六個階段: 業(yè)務邏輯思維導圖 功能——業(yè)務邏輯思維導圖 基本功能模塊關(guān)系 ...

    yzzz 評論0 收藏0
  • App后臺api開發(fā)前的準備

    摘要:負責從拉取數(shù)據(jù)源,把數(shù)據(jù)源分詞,建立索引搜索模塊工作流程如下模塊從中拉取數(shù)據(jù)模塊用經(jīng)過中文分詞后的數(shù)據(jù)建立索引客戶端向模塊發(fā)起搜索請求模塊查找索引中的數(shù)據(jù)模塊得到索引中符合要求的數(shù)據(jù)的等數(shù)據(jù)把數(shù)據(jù)返回給客戶端 (整理自《App后臺開發(fā)運維和架構(gòu)實踐》 作者:曾健生) 一、從業(yè)務邏輯中提煉API接口 此過程可分為六個階段: 業(yè)務邏輯思維導圖 功能——業(yè)務邏輯思維導圖 基本功能模塊關(guān)系 ...

    laoLiueizo 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<