應用場景:數(shù)據(jù)以文檔的形式保存于couchdb,現(xiàn)在需要導入到elasticsearch建索引以支持全文檢索。
不要去想著從couchdb讀數(shù)據(jù),然后調elasticsearch接口建索引了。logstash能很方便的完成你想要的工作,你所要做的工作就是裝上logstash。 然后在conf里面寫一個配置文件。比如db2es.conf .
input {
couchdb_changes {
db => "media"
host => "192.168.0.70"
port => 5984
codec => "json"
username => "rdd"
password => "rdd1qaz2wsx"
initial_sequence => 0 #this is only required for the an initial indexing
#keep_revision=>true
}
}
output {
elasticsearch{
#action => "%{[@metadata][action]}"
action =>"index"
document_id => "%{[@metadata][_id]}"
hosts => "192.168.0.70:9200"
#index => "monitor-%{+YYYY.MM.dd}"
index => "media"
document_type => "doc"
}
if [@metadata][action] == "delete" {
elasticsearch{
action => "%{[@metadata][action]}"
#action =>"index"
document_id => "%{[@metadata][_id]}"
hosts => "192.168.0.70:9200"
#index => "monitor-%{+YYYY.MM.dd}"
index => "media"
document_type => "doc"
}
}
#stdout {} #enable this option for debugging purpose
}
接下來就是運行命令
bin/logstash agent -f conf/db2es.conf &
這個配置文件比較好用了。通過action可以輕松的創(chuàng)建和刪除索引。通過引用couchdb的document_id可以防止重復建索引。
當然它本身是根據(jù)couchdb的字段類型在elasticsearch里面建索引的,比如支持時間類型,但是couchdb似乎對時間類型的支持不太好,始終是以utc+0創(chuàng)建時間字段,所以在數(shù)據(jù)進入couchdb的時候最好先做處理。比如你存儲的時間是UTC+8, couchdb會自動減去8小時作為你的存儲時間。那么你在導入couchdb之前就要把時間多加上8小時,這樣couchdb減去8小時后就正好是你想要的時間。再不然就需要在同步到elasticsearch的時候處理一下以保證索引時間在正確的時區(qū)。