现在的位置: 首页 > 综合 > 正文

[Ruby on Rails] 使用IndexTank做雲端搜尋

2018年01月10日 ⁄ 综合 ⁄ 共 1627字 ⁄ 字号 评论关闭

[Ruby on Rails] 使用IndexTank做雲端搜尋

indextank

在「T客邦網站開發實務 – 網站開發時,不做會死的工作。」一文有提到 – 「很多東西自己造輪子太累了,不但費錢也費時,還要花人力在維護上面,實在不值得。」,趁假日比較有閒,來寫一篇IndexTank的介紹。

先來個Ruby on Rails常用搜尋引擎Sphinx(Gem:thinking_sphinx)和IndexTank的比較:

  sphinx indextank
優點
  • 免費
  • 服務建立在自己家。
  • 重開及建檔速度快。
  • 上手容易。
  • 搜尋速度快。
  • 中文搜尋準確度高。
  • 客服專業且回覆速度快。
缺點
  • 學習較困難,需先架起Spnix才可供Ruby做應用。
  • 中文斷字ok,但「繁體」中文斷詞目前找不到資源,導致搜尋結果較差。(簡體可使用coreseek)
  • 要錢,量大不便宜。
  • snippet(截關鍵字段落)因為編碼問題不支援中文。
  • 建檔速度慢,須搭配delayed_job去處理,不然整個網站會crash。
  • server端不能出問題。(測試兩三個月曾經掛掉過一次)。

註冊

1.先到 此處 註冊一個月免費帳號。(不用一分鐘!)

indextank-signup


2.按下"create index"的按鈕,並打入你要建立的index名稱,這邊用test_index當範例。

indextank-insert-index


3.接者在畫面左下角會看到"PRIVATE URL",把他記住就可以開始寫Code了。

indextank-api


安裝Gem

Gemfile加上

1
gem "indextank"

執行"bundle install"


建檔

1
2
3
4
5
6
7
8
9
10
# 建立index後取得的PRIVATE URL
api_client = IndexTank::Client.new
'YOUR PRIVATE URL'
#test_index為剛剛建立的index名稱
test_index = api_client.indexes
'test_index'  
#塞id為1的資料,有欄位title和content
test_index.document("1").add({
:title =>
"post 1":content
=> 'I love Bioshock' 
})
test_index.document("2").add({
:title =>
"post 2", :content
=> 'Need cheats for Bioshock'
})
test_index.document("3").add({
:title =>
"post 3", :content
=> 'I love Tetris'
})

假設要將所有Post model的資料都建檔

1
2
3
Post.all.each
do  |post|
    test_index.document("#{post.id}").add({
:title => post.title,
:content => post.content })
end

搜尋

1
2
3
4
5
6
7
8
#搜尋love
test_index.search
'love'
#搜尋love,抓取title和content欄位,注意title和content中間逗點禁止有空格!不然後面的資料抓不到
test_index.search('love',
:fetch =>
'title,content' )
#搜尋包含love的片段,回傳擷取好的content,目前中文無法使用!
test_index.search('love',
:snippet =>
'content')

更新

1
2
# 使用相同id重新傳一次。
test_index.document("1").add({
:title =>
"post 1":content
=> 'I love Bioshock' 
})

刪除

1
test_index.document("1").delete

結論

搜尋最主要的是速度和準確度,雖然IndexTank的服務要花錢,但搜尋結果實在是很令人滿意!且支援的語言不只Ruby,還包括 Python, Php, Java,加上學習門檻真的非常低(學習到使用不用花兩小時),未來淺力不可小覷!

抱歉!评论已关闭.