主机环境: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 , |
26 |
"term_vector" : "with_positions_offsets" }, |
33 |
"term_vector" : "with_positions_offsets" }, |
34 |
u 'dirpath' : { 'boost' : 1.0 , |
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 ] |