1+ # encoding: utf-8
2+ __author__ = 'zhanghe'
3+
4+ import pyes
5+
6+
7+ conn = pyes .ES (['127.0.0.1:9200' ]) # 连接es
8+
9+
10+ def create ():
11+ conn .create_index ('test-index' ) # 新建一个索引
12+
13+ # 定义索引存储结构
14+ mapping = {u'id' : {'boost' : 1.0 ,
15+ 'index' : 'not_analyzed' ,
16+ 'store' : 'yes' ,
17+ 'type' : u'string' ,
18+ "term_vector" : "with_positions_offsets" },
19+ u'user_id' : {'boost' : 1.0 ,
20+ 'index' : 'not_analyzed' ,
21+ 'store' : 'yes' ,
22+ 'type' : u'string' ,
23+ "term_vector" : "with_positions_offsets" },
24+ u'nick' : {'boost' : 1.0 ,
25+ 'index' : 'analyzed' ,
26+ 'store' : 'yes' ,
27+ 'type' : u'string' ,
28+ "term_vector" : "with_positions_offsets" },
29+ u'city' : {'boost' : 1.0 ,
30+ 'index' : 'analyzed' ,
31+ 'store' : 'yes' ,
32+ 'type' : u'string' ,
33+ "term_vector" : "with_positions_offsets" },
34+ }
35+
36+ conn .put_mapping ("test-type1" , {'properties' : mapping }, ["test-index" ]) # 定义test-type
37+ conn .put_mapping ("test-type2" , {"_parent" : {"type" : "test-type1" }}, ["test-index" ]) # 从test-type继承
38+
39+ # 插入索引数据
40+ # {"id":"1", "user_id":"u1", "nick":u"压力很大", "city":u"成都"}: 文档数据
41+ # test-index:索引名称
42+ # test-type: 类型
43+ # 1: id 注:id可以不给,系统会自动生成
44+ conn .index ({"id" : "1" , "user_id" : "u1" , "nick" : u"压力很大" , "city" : u"成都" }, "test-index" , "test-type1" , 1 )
45+ conn .index ({"id" : "2" , "user_id" : "u2" , "nick" : u"压力很小" , "city" : u"北京" }, "test-index" , "test-type1" )
46+ conn .index ({"id" : "3" , "user_id" : "u3" , "nick" : u"没有压力" , "city" : u"成都" }, "test-index" , "test-type1" )
47+
48+ conn .default_indices = ["test-index" ] # 设置默认的索引
49+ conn .refresh () # 刷新以获得最新插入的文档
50+
51+
52+ def query ():
53+ # 查询nick中包含压力的记录
54+ q = pyes .StringQuery (u"压力" , 'nick' )
55+ results = conn .search (q )
56+
57+ for r in results :
58+ print u"查询nick中包含压力的记录" , r ['nick' ], r ['city' ]
59+
60+ # 查询city中包含成都的数据
61+ q = pyes .StringQuery (u"成都" , 'city' )
62+ results = conn .search (q )
63+
64+ for r in results :
65+ print u"查询city中包含成都的数据" , r ['nick' ], r ['city' ]
66+
67+ # 查询nick中包含很小或没有的数据
68+ q = pyes .StringQuery (u"很小 OR 没有" , 'nick' )
69+ results = conn .search (q )
70+
71+ for r in results :
72+ print u"查询nick中包含很小或没有的数据" , r ['nick' ], r ['city' ]
73+
74+
75+ if __name__ == '__main__' :
76+ # create()
77+ query ()
0 commit comments