python 操作 Elasticsearch(一)

1、python连接elasticsearch数据库

from elasticsearch import Elasticsearch
from elasticsearch import helpers

es = Elasticsearch(['你的elasticsearch的外网连接'], http_auth=('数据库的用户名', '密码'),timeout=60,max_retries=10,retry_on_timeout=True)

2、建索引(2分片,2副本)

CREATE_BODY = {
    "settings": {
        "number_of_shards": 2,    # 分片的个数
        "number_of_replicas": 2    # 副本的个数
    },
    "mappings": {
        "properties": {
            "Id": {
            "type": "keyword",
            },
            "name": {
                "type": "keyword"
            },
            "adress": {
                "type": "keyword"
            },
            "education": {
                "type": "keyword"
            },
            "english_name": {
                "type": "keyword"
            },
            "phone_number": {
                "type": "keyword"
            },
            "money": {
                "type": "keyword"
            },
            "population": {
                "type": "keyword"
            },
            "job": {
                "type": "keyword"
            },
            "datetime": {
                "type": "keyword"
            }
        }        
    }
}
# 创建一个名为demo的表
es.indices.create(index = 'demo',body =CREATE_BODY) 

3、下载一个叫elasticsearch-head的程序,可以看到索引的详细信息。

在这里插入图片描述

刚刚我已经创建索引了,现在通过elasticsearch-head来看一看这个索引的结构。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
可以看到,已按代码创建好了索引。接下来就是添加数据了。

4、添加数据

4.1、创建对应的dataframe

先随便创建一个测试数据,再插入进去。(这里使用的方法是:创建一个dataframe,然后转json,再插入进去)。因为我比较喜欢用pandas处理数据,所以索性就用pandas的dataframe插入数据。毕竟,读取csv的时候也方便。

import pandas as pd

dict = {'Id':[1,2],'name':['赵','钱'],'adress':['广东省','湖南省'],\
        'education':['小学','初中'],'english_name':['qian','zhao'],\
        'phone_number':['12345678910','10987654321'],'money':[100,300],\
        'population':['7','3'],'job':['doctor','student'],'datetime':['2020-09-27','2020-09-25']}
df = pd.DataFrame(dict)

在这里插入图片描述

4.2、插入数据

4.2.1、计算创建花了多少时间的函数

import time
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        print('共耗时约{:.2f}秒'.format(time.time() - start))
        return res
    return wrapper

4.2.2、将dataframe转化为json并插入对应索引的函数

import json
def df_to_es(df):
    df_as_json = df.to_json(orient='records', lines=True)
    action = []
    for json_document in df_as_json.split('\n'):
        action.append({
            '_index': 'demo',
            '_type': '_doc',
            '_source': json.loads(json_document)
        })
        if len(action) > 10000:
            helpers.bulk(es, action)
            action = []
    helpers.bulk(es, action)

4.2.3、插入n条数据进入对应索引的函数

@timer
def batch_data_process(n,df_demo):
    list = []

    for i in range(n):
        list.append(df_demo.to_dict(orient='records')[i])

    df = pd.DataFrame(list)
    df_to_es(df)

4.2.4、插入dataframe中前2条数据,并查看是否插入成功。

batch_data_process(2,df)

在这里插入图片描述
我们可以看到,数据已经成功插入了。其实这个插入,主要还是以字典和列表为主,之所以展示的是dataframe,是因为大部分实际情况都是从csv导出数据为dataframe,然后经过数据处理之后,再插入es的,所以随大流,分享一下我是如何将pandas的dataframe插入es的对应索引中。

5、查看数据(全部数据)

demo = es.search(index="demo",doc_type="_doc",
              filter_path=["hits.hits._source.*"],size=10000)
df_demo = pd.DataFrame([demo['hits']['hits'][i]['_source'] for i in range(len(demo['hits']['hits']))])

在这里插入图片描述

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
利用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()) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会点东西的普通人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值