elasticsearch,lucene结合使用
案例
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host':'ip地址','port':9200}, timeout=1000]) # 连接es,设置超时时间1000秒
'''如果需要用户名密码认证,加上 http_auth=('root', '111111') 参数 root用户名 111111 密码'''
查询案例
res=es.search(index='test', q='name:hihi OR name:lucy')['hits']['hits'] # 查询索引为test下,其中name为haha 或者name首字母为a,b,c的所有文档。
''' 如果想要指定文档 加上 doc_type='test_log' 参数 test_log为指定文档的名称'''
##### 查询结果
[{'_index': 'test', '_type': 'test_one', '_id': 'AXfJH3sRISkIKOZVU8d1', '_score': 0.2876821, '_source': {'name': 'lucy', 'sex': 'girl', 'work': 'singer', 'like': 'sing'}}, {'_index': 'test', '_type': 'test_one', '_id': '2', '_score': 0.2876821, '_source': {'name': 'hihi', 'sex': 'boy', 'work': 'sleep', 'like': 'sleep'}}]
es常用参数
index - 索引名
q - 查询指定匹配 使用Lucene查询语法
from_ - 查询起始点 默认0
doc_type - 文档类型
size - 指定查询条数 默认10
field - 指定字段 逗号分隔
sort - 排序 字段:asc/desc
body - 使用Query DSL
scroll - 滚动查询
lucene语法
代码案例( {} [] )
{}尖括号表示不包含最小值和最大值
[]方括号表示包含最小值和最大值
eg:
{3 TO 6} --------- 4,5
[3 TO 6] --------- 3,4,5,6
{3 TO 6] --------- 4,5,6
[3 TO 6} --------- 3,4,5
res = es.search(index='test', doc_type='test_one')
res1 = es.search(index='test', doc_type='test_one', q="age:[11 TO 15]")
res2 = es.search(index='test', doc_type='test_one', q="age:{11 TO 15}")
res3 = es.search(index='test', doc_type='test_one', q="age:{11 TO 15]")
res4 = es.search(index='test', doc_type='test_one', q="age:[11 TO 15}")
print(res['hits']['hits'], 'res---------------')
print(res1['hits']['hits'], 'age:[11 TO 15]------------')
print(res2['hits']['hits'], 'age:{11 TO 15}----------')
print(res3['hits']['hits'], 'age:{11 TO 15]----------')
print(res4['hits']['hits'], 'age:[11 TO 15}----------')
结果展示
[{'_index': 'test', '_type': 'test_one', '_id': 'AXfJH3sRISkIKOZVU8d1', '_score': 1.0, '_source': {'name': 'lucy', 'sex': 'girl', 'work': 'singer', 'like': 'sing', 'age': 11}}, {'_index': 'test', '_type': 'test_one', '_id': 'AXfMs8e2ISkIKOZVU8eB', '_score': 1.0, '_source': {'name': 'Cindy', 'sex': 'girl', 'work': 'loo', 'like': 'loo', 'age': 13}}, {'_index': 'test', '_type': 'test_one', '_id': 'AXfMtn7WISkIKOZVU8eC', '_score': 1.0, '_source': {'name': 'Cindy', 'sex': 'girl', 'work': 'loo', 'like': 'loo', 'age': 15}}, {'_index': 'test', '_type': 'test_one', '_id': '2', '_score': 1.0, '_source': {'name': 'hihi', 'sex': 'boy', 'work': 'sleep', 'like': 'sleep', 'age': 17}},