Python依赖
# elasticsearch 支持大版本 7,8没有测试过
# 默认安装 es7.10.0
elasticsearch==7.10.0
使用方法简述
from elasticsearch import Elasticsearch
from es_orm.es_helper import DefaultEsHelper, Q, Sort, ESPagination
from es_orm.es_helper import TextField, Collapse, Update
ES_INSTANCE = Elasticsearch()
ES_HELPER = DefaultEsHelper(ES_INSTANCE)
# 判断字段是否存在
q = Q.filter('exists', field='index_field_name')
result = ES_HELPER.search(index=[index], body=q())
# 与逻辑
q += Q.must('term', name='xiaoming', age=12)
result = ES_HELPER.search(index=[index], body=q())
# 或逻辑
q |= Q.filter('term', name='john')
result = ES_HELPER.search(index=[index], body=q())
# 排序
sort = Sort(age='asc', score='desc')
result = ES_HELPER.search(index=[index], body=q(sort=sort))
# 分页
pagination = ESPagination()
result = ES_HELPER.search(index=[index], body=q(pagination=pagination))
# 脚本更新
updater = Update(field1='value1', field2='value2')
result = ES_HELPER.search(index=[index], body=q(updater=updater))
# 去重
collapse = Collapse('field_name')
result = ES_HELPER.search(index=[index], body=q(collapse=collapse))
# 所有条件一起
result = ES_HELPER.search(index=[index], body=q(sort=sort, pagination=pagination, collapse=collapse, updater=updater, collapse=collapse))
# 创建index
DefaultEsHelper.create_mapping(ES_HELPER.es, [TextFeild('demo')], [index])
# 删除index
DefaultEsHelper.del_mapping(ES_HELPER.es, [index])
# 是否存在符合条件的记录
ES_HELPER.exists(index=[index], body=q())
# 查询更新
ES_HELPER.update_by_query(index=[index], body=q(), data={'name':'new_name'})
# 相比官方 reindex 更稳定的 reindex 实现
ES_HELPER.reindex(src, dst, filters, size=200)
# 批量插入
ES_HELPER.bulk_insert(index=[index], body=[{'name':'xiaoming'}, {'name':'zhangsan'}])
# 单条记录插入
ES_HELPER.insert(index=[index], body={'name': 'xiaowang'})
安装命令
pip install es-orm