主機環境:Ubuntu 13.04
Python版本:2.7.4
官方站點:http://www.elasticsearch.com/
中文站點:http://es-cn.medcl.net/
下面一段介紹引用自中文站點:
好吧,假如你建了一個web站點或者是一個應用程序,你就可能會需要添加搜索功能(因爲這太有必要了),而事實上讓搜索跑起來是有難度的,我們不僅想要搜索的速度快,而且還要安裝方便(最好是無痛安裝),另外模式定義要非常自由(schema free),可以通過HTTP以JSON格式的數據來進行索引,服務器必須是一直可用的(HA高可用,這個不能丟),從一臺機器能夠擴展到成千上萬臺,然後搜索必須是實時的(real-time),使用起來一定要簡單、支持多租戶,我們需要一整套的解決方案,並且是爲雲構建的。
“讓搜索更簡單”,這是我們的宣言,“並且要酷,像盆景一樣”
elasticsearch 的目標是解決上面的所有問題以及更多。她是開源的(Apache2協議),分佈式的,RESTful的,構建在Apache Lucene之上的的搜索引擎.
1 、分佈式服務器的安裝:
sudo service elasticsearch start
來啓動服務。
2、安裝pyes客戶端
使用命令
安裝elasticsearch的python的組件。
3、安裝pyes的中文分詞組件
然後移動的elasticsearch的安裝目錄/usr/share/elasticsearch/analysis-ik/,
修改配置文件/etc/elasticsearch/elasticsearch.yml
設置插件的路徑
path.plugins: /usr/share/elasticsearch/plugins
並添加分詞組建配置
6 | type: org.elasticsearch.index.analysis.IkAnalyzerProvider |
最後下載IK分詞使用的詞典
- cd /etc/elasticsearch
- wget http://github.com/downloads/medcl/elasticsearch-analysis-ik/ik.zip –no-check-certificate
- unzip ik.zip
- rm ik.zip
重啓elasticsearch服務即可。
4、建立索引
09 | class IndexFiles( object ): |
10 | def __init__( self ,root): |
11 | conn = ES( '127.0.0.1:9200' , timeout = 3.5 ) |
13 | conn.delete_index(INDEX_NAME) |
17 | conn.create_index(INDEX_NAME) |
20 | mapping = {u 'content' : { 'boost' : 1.0 , |
25 | "searchAnalyzer" : "ik" , |
26 | "term_vector" : "with_positions_offsets" }, |
27 | u 'name' : { 'boost' : 1.0 , |
32 | "searchAnalyzer" : "ik" , |
33 | "term_vector" : "with_positions_offsets" }, |
34 | u 'dirpath' : { 'boost' : 1.0 , |
39 | "searchAnalyzer" : "ik" , |
40 | "term_vector" : "with_positions_offsets" }, |
43 | conn.put_mapping( "test-type" , { 'properties' :mapping}, [INDEX_NAME]) |
45 | self .addIndex(conn,root) |
47 | conn.default_indices = [INDEX_NAME] |
50 | def addIndex( self ,conn,root): |
52 | for root, dirnames, filenames in os.walk(root): |
53 | for filename in filenames: |
54 | if not filename.endswith( '.txt' ): |
56 | print "Indexing file " , filename |
58 | path = os.path.join(root,filename) |
60 | contents = unicode ( file .read(), 'utf-8' ) |
63 | conn.index({ 'name' :filename, 'dirpath' :root, 'content' :contents},INDEX_NAME, 'test-type' ) |
65 | print 'no contents in file %s' ,path |
69 | if __name__ = = '__main__' : |
70 | IndexFiles( './txtfiles' ) |
5、搜索並高亮顯示
08 | conn = ES( '127.0.0.1:9200' , timeout = 3.5 ) |
09 | sq = StringQuery(u '世界末日' , 'content' ) |
10 | h = HighLighter([ '<b>' ], [ '</b>' ], fragment_size = 20 ) |
12 | s = Search(sq,highlight = h) |
13 | s.add_highlight( "content" ) |
14 | results = conn.search(s,indices = 'txtfiles' ,doc_types = 'test-type' ) |
18 | if (r._meta.highlight.has_key( "content" )): |
19 | r[ 'content' ] = r._meta.highlight[u "content" ][ 0 ] |