【Python】Elasticsearch 常规用操作封装

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 = ESPag
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
利用Python操作Elasticsearch可以使用elasticsearchelasticsearch-dsl这两个库,也可以使用更为简单的es-pandas库。其中,elasticsearch库提供了与Elasticsearch交互的低级接口,而elasticsearch-dsl库则提供了更高级别的查询构建器和对象映射器。es-pandas库则提供了一种将Elasticsearch数据转换为pandas DataFrame的简单方法。 以下是一个使用elasticsearch库进行查询的例子: ```python from elasticsearch import Elasticsearch # 连接到Elasticsearch es = Elasticsearch() # 查询所有文档 res = es.search(index="my_index", body={"query": {"match_all": {}}}) # 输出结果 for hit in res['hits']['hits']: print(hit['_source']) ``` 以下是一个使用elasticsearch-dsl库进行查询的例子: ```python from elasticsearch import Elasticsearch from elasticsearch_dsl import Search # 连接到Elasticsearch es = Elasticsearch() # 创建查询对象 s = Search(using=es, index="my_index").query("match", title="python") # 执行查询并输出结果 response = s.execute() for hit in response: print(hit.title) ``` 以下是一个使用es-pandas库将Elasticsearch数据转换为pandas DataFrame的例子: ```python from es_pandas import es_pandas # 将Elasticsearch数据转换为pandas DataFrame df = es_pandas.DataFrame({ "host": {"field": "host.keyword"}, "response": {"field": "response_time_ms"}, "timestamp": {"field": "@timestamp", "dtype": "datetime64[ns]"} }, es_url="http://localhost:9200", es_index_pattern="my_index-*") # 输出DataFrame print(df.head()) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值