Elasticsearch的python使用

import json
import datetime
import time
from uuid import uuid4
from elasticsearch import Elasticsearch
from loguru import logger
from typing import List


def now():
    return int(time.time() * 1000)

class ESClient(object):
    def __init__(self):
        self.client = Elasticsearch(["http://9.134.105.179:9200"],
                                    http_auth=("elastic", pwd),
                                    timeout=30)
        self.index = "loleinaliao_test"

    def add_record(self, record):
        record_id = uuid4()
        es_rsp = self.client.index(index=self.index, body=record, id=record_id)
        logger.info('add es records, name: {}, id: {}, rsp: {}', record.get('name'), record_id, es_rsp)


    def update_record(self, body, name):
        source_scripts = []
        for k in body:
            source_scripts.append('ctx._source.{}=params.{}'.format(k, k))
        source_script = ';'.join(source_scripts)
        es_rsp = self.client.update_by_query(index=self.index,
                                             conflicts='proceed',
                                             body={"query": {"term": {"name": name}},
                                                   "script": {"source": source_script,
                                                              "lang": "painless",
                                                              "params": body}})
        print(es_rsp)

  

    def search_records(self, busi: str, table_type: str, env: str,  size=10, scroll_id=None, time_range=None):
        must = []
        must_not = []
        must.append({"match_phrase": {"busi": busi}})
        must.append({"match_phrase": {"type": table_type}})
        must.append({"match_phrase": {"env": env}})
        must.append({"match_phrase": {"status": "ok"}})
        now_time = datetime.datetime.now() - datetime.timedelta(hours=8)
        start = now()
        if not time_range:
            collect_time = {
                "lt": now_time
            }
        else:
            start_time = now_time - datetime.timedelta(days=time_range[0])
            end_time = now_time - datetime.timedelta(days=time_range[1])
            collect_time = {
                "lt": end_time,
                "gte": start_time
            }
        search_body = {
            "query": {
                "bool": {
                    "must": must,
                    "must_not": must_not,
                    "filter": {
                        "range": {
                            "collect_time": collect_time
                        }
                    }
                }
            },
            "size": size
        }
        if scroll_id:
            es_rsp = self.client.scroll(scroll_id=scroll_id,
                                        scroll='1m')
        else:
            es_rsp = self.client.search(index=self.index,
                                        body=search_body,
                                        scroll='1m')
        print(es_rsp)
        hits = es_rsp['hits']['hits']
        if hits:
            hits = [hit['_source'] for hit in hits]
        else:
            pass
        return hits, es_rsp.get('_scroll_id'), es_rsp['hits']['total']['value']
    


ES_CLIENT = ESClient()

按需求封装好es的client,里面包含常用的一些操作,比如add,update,serach 等,然后client使用大概如下

from loleinaliao.elasticsearch.es_client import ES_CLIENT
import datetime

def _gen_es_add_record(msg: dict, rule: dict, env: str, host: str, tags: list, delay: int, case_full_path: str):
    db_table = '{}.{}'.format(msg['database'], msg['table'])
    sql = "SELECT * FROM {} WHERE {};".format(db_table, rule["where_condition"])
    record = {
        'name': rule["name"],
        'type': rule["type"],
        'busi': rule["busi"],
        'env': env,
        'desc': rule["desc"],
        'host': host,
        'sql': sql,
        'status': rule["status"],
        'tags': tags,
        'case_full_path': case_full_path,
        'create_time': datetime.datetime.now(),
        'collect_time': datetime.datetime.now() - datetime.timedelta(hours=8) + datetime.timedelta(hours=delay),
        'modify_time': datetime.datetime.now() - datetime.timedelta(hours=8),
    }
    return record


def gen_record():
    msg ={
        "database": "database2",
        "table":"table2"
    }
    rule={
        "name":"name2",
        "type": "type2",
        "busi":"busi2",
        "desc":"desc2",
        "status":"ok",
        "where_condition":"flsate =2",
    }
    case_full_path = "base_test.py"
    delay_collect_hours = 1
    env ='bvt'
    host='12233445'
    tags ='tags1'
    record = _gen_es_add_record(msg, rule, env, host, tags, delay_collect_hours, case_full_path)
    ES_CLIENT.add_record(record)


def update_record():
    name = "name1"
    body = {"status" : "ok"}
    ES_CLIENT.update_record(body, name)

def search_records():
    return ES_CLIENT.search_records("busi1", "type1","bvt")



if __name__ == '__main__':
    # gen_record()
    # update_record()
    hits,_,_ = search_records()
    print(hits)

### 回答1: Python可以使用Elasticsearch来进行搜索和分析数据。Elasticsearch是一个开源的搜索引擎,它可以快速地处理大量的数据,并提供高效的搜索和分析功能。Python可以通过Elasticsearch的API来与Elasticsearch进行交互,从而实现搜索和分析数据的功能。在使用PythonElasticsearch时,需要安装ElasticsearchPython客户端库,例如elasticsearch-py,然后使用Python代码来调用Elasticsearch的API。通过PythonElasticsearch的结合,可以实现各种搜索和分析数据的应用,例如搜索引擎、日志分析、数据挖掘等。 ### 回答2: Python作为一种流行的编程语言,具有强大的数据处理和分析能力,在数据科学和机器学习领域得到广泛应用。在数据处理过程中,搜索引擎是非常重要的。Elasticsearch是一款基于Lucene的开源搜索引擎,可以帮助开发人员快速实现文本搜索和数据分析。PythonElasticsearch的结合,可以极大地增强数据处理和分析的能力。 Python作为通用编程语言,可以通过其支持的第三方库来操作ElasticsearchPythonelasticsearch模块提供了与Elasticsearch交互的API,可以执行多种搜索操作。 通过Python连接Elasticsearch,开发人员可以提供各种搜索功能。例如,可以实现全文搜索、模糊搜索、正则表达式搜索、短语搜索、过滤、聚合和分析功能。Pythonelasticsearch模块还支持在Elasticsearch中创建和管理索引,创建和管理文档、进行批量操作,查询聚合等。 除了搜索功能,Pythonelasticsearch模块还提供了对索引和文档的管理功能。可以从Python代码中创建、删除、修改和查询文档和索引,甚至可以创建与分片和节点的连接池。这个模块广泛应用于设置表单、数据库和搜索引擎。 总之,PythonElasticsearch的结合可以提高数据处理和分析的效率。开发人员可以使用Pythonelasticsearch模块来探索和查询数据,使得数据分析过程更加便捷。 ### 回答3: Python是一个十分流行的编程语言,而Elasticsearch是一个免费、开源、分布式、高性能的搜索引擎,可以使大量数据的检索更加简便和高效。因此,Python应用程序往往会使用Elasticsearch来完成搜索部分。 首先,Python可以直接使用ElasticsearchPython客户端API来对Elasticsearch进行调用和操作。有多个Python库来实现与Elasticsearch通信的功能,其中最流行的是elasticsearch-py库。此库使用简单,可方便地在Python代码中使用Elasticsearch进行索引、搜索、更新和删除操作。 其次,使用PythonElasticsearch进行搜索功能的优化是一个很重要的议题。因为Elasticsearch是基于Lucene建立的,而Lucene是一个搜索引擎的底层库,包含了基本的搜索功能。Python可以在这一基础上进一步优化搜索体验,例如,通过分析页面访问历史数据和搜索记录,使用机器学习算法,可以更加精确地为用户推荐搜索结果。 另外,Python的pandas库可以结合Elasticsearch进行数据流处理、读写和分析。可以使用pandas.DataFrame来查询Elasticsearch中的数据,这个DataFrame也可以将计算的结果重新写回到Elasticsearch中。这个操作和pandas经常使用的SQL的DataFrames语法非常相似。这个特性特别对那些需要海量数据处理的团队有很大的帮助。 总之,PythonElasticsearch的结合可以提升搜索的精准度和效率,同时也使得数据的处理和分析更加便捷。这是一个十分强大和有用的应用场景,可以为数据科学家、大数据分析师、网络工程师等等提供极大的帮助和优势。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值