python elasticsearch 查询简单脚本

入职的新公司,中台使用的elasticsearch给我们提供的数据,已经测了两三个需求了,但不清楚如何查询数据,用例评审时直接说的不校验数据准确性,只做展示校验。然后,上线后发现了一堆bug,虽说没我啥责任吧,但心里总是觉得不是很舒服,于是开始了elasticsearch的简单入门之旅


几个关键概念

  • index:类似于sql中的表
  • type:类似于SQL中的库,一般查询的时候无需使用(或者也是我没使用)
  • hits:返回的数据都在这个key下面
  • hits.total:返回数据的数据数量

有这个概念后,根据提供的如何取值需求,就可以直接编写sql语句了:

select 字段 from index where 条件;

在线转换平台:http://www.ischoolbar.com/EsParser/

这样手工测试就可以玩了。

from elasticsearch import Elasticsearch
import pandas

from config.es_config import *


############################################
# 写的很简单,参数严格按要求给,想优化请自行优化 #
############################################


class DataBoard():
    def __init__(self):
        self.es = Elasticsearch([HOST], http_auth=(USERNAME, PASSWORD), scheme='http', port=PORT, timeout=30)

    def create_body(self, fields, hospital_id, st_day="2021-05-01", et_day="2021-06-10"):
        body = {"query": {
            "bool": {"filter": [{"bool": {"must": [{"match_phrase": {"hospital_id": {"query": str(hospital_id)}}}]}},
                                {"range": {"st_day": {"gte": st_day, "time_zone": "+08:00",
                                                      "lte": et_day}}}]}},
            "sort": [{"st_day": {"order": "DESC"}}], "_source": {
                "include": fields}}
        return body

    def search(self, index, body, size=100):
        '''
        查询
        :param index:
        :param body:
        :param size: 返回的数量
        :return:
        '''
        return self.es.search(index=index, body=body or {'query': {'match_all': {}}}, size=size)


if __name__ == '__main__':
    # 查询索引
    index = 'dws_hospital_topics_d'
    # 查询字段
    fields = ["msg_2_user_cnt", "tel_user_call_user_cnt", "business_opp_enquiry_price_user_cnt"]
    # 查询的机构(一般都是66)
    hospital_id = 66

    pandas.set_option('display.width', None)  # 设置字符显示宽度

    pandas.set_option('display.max_rows', None)  # 设置显示最大行

    pandas.set_option('display.max_columns', None)  # 设置显示最大列

    pandas.set_option('max_colwidth', None)

    data = DataBoard()
    body = data.create_body(fields=fields, hospital_id=hospital_id)
    result = data.search(index=index, body=body)
    print(result['hits']['hits'])
    # 删除掉一些不需要看的字段
    for d in result['hits']['hits']:
        d.pop('_index')
        d.pop('_type')
        d.pop('_score')
    print(pandas.DataFrame(result['hits']['hits']))

其中用到pandas处理了一下数据,方便控制台可视化展示

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用 Python 自动部署 Elasticsearch脚本,你可以根据自己的需要进行修改和调整: ```python import os import shutil import subprocess # 定义 Elasticsearch 版本和下载链接 ES_VERSION = "7.10.2" ES_DOWNLOAD_URL = f"https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{ES_VERSION}-linux-x86_64.tar.gz" # 定义 Elasticsearch 安装目录和数据目录 ES_INSTALL_DIR = "/opt/elasticsearch" ES_DATA_DIR = "/var/lib/elasticsearch" # 下载 Elasticsearch 安装包 subprocess.run(["wget", ES_DOWNLOAD_URL], check=True) # 解压安装包并移动到安装目录 shutil.unpack_archive(f"elasticsearch-{ES_VERSION}-linux-x86_64.tar.gz", "/tmp") shutil.move(f"/tmp/elasticsearch-{ES_VERSION}", ES_INSTALL_DIR) # 创建数据目录并设置权限 os.makedirs(ES_DATA_DIR, exist_ok=True) subprocess.run(["chown", "-R", "elasticsearch:elasticsearch", ES_DATA_DIR], check=True) # 创建 systemd 服务文件 with open("/etc/systemd/system/elasticsearch.service", "w") as f: f.write(f"""[Unit] Description=Elasticsearch After=network.target [Service] Type=simple User=elasticsearch Group=elasticsearch WorkingDirectory={ES_INSTALL_DIR} ExecStart={ES_INSTALL_DIR}/bin/elasticsearch Restart=on-failure [Install] WantedBy=multi-user.target """) # 重新加载 systemd 服务文件并启动 Elasticsearch 服务 subprocess.run(["systemctl", "daemon-reload"], check=True) subprocess.run(["systemctl", "enable", "elasticsearch"], check=True) subprocess.run(["systemctl", "start", "elasticsearch"], check=True) ``` 注意,以上脚本需要以 root 用户权限运行,并且需要提前创建好 elasticsearch 用户和组,并将其添加到 sudoers 文件中。另外,该脚本只能在 Linux 系统上运行。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值