在「T客邦網站開發實務 – 網站開發時,不做會死的工作。」一文有提到 – 「很多東西自己造輪子太累了,不但費錢也費時,還要花人力在維護上面,實在不值得。」,趁假日比較有閒,來寫一篇IndexTank的介紹。
先來個Ruby on Rails常用搜尋引擎Sphinx(Gem:thinking_sphinx)和IndexTank的比較:
![]() | ![]() | |
---|---|---|
優點 |
|
|
缺點 |
|
|
註冊
1.先到 此處 註冊一個月免費帳號。(不用一分鐘!)
2.按下"create index"的按鈕,並打入你要建立的index名稱,這邊用test_index當範例。
3.接者在畫面左下角會看到"PRIVATE URL",把他記住就可以開始寫Code了。
安裝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,加上學習門檻真的非常低(學習到使用不用花兩小時),未來淺力不可小覷!