Python读写ElasticSearch【自用】


基本调用

安装

conda insatll elasticsearch

基本调用

from elasticsearch import Elasticsearch

HOSTS = 'http://abc.com'
INDEX = 'abc'  # 索引(类似MySQL库名)

es = Elasticsearch(HOSTS)
js = es.search(INDEX, {
   'query': {
   'match_all': {
   }}})
print(js)
>>> from elasticsearch import Elasticsearch

# 默认连接localhost:9200
>>> es = Elasticsearch()

# 写
>>> es.index(index="my-index", doc_type="test-type", id=42, body={
   "any": "data"})
{
   '_id': '42', '_index': 'my-index', '_type': 'test-type', '_version': 1, 'ok': True}

# 读
>>> es.get(index="my-index", doc_type="test-type", id=42)['_source']
{
   'any': 'data'}

封装自用

from elasticsearch import Elasticsearch

HOSTS = 'http://abc.com'
INDEX = 'abc'  # 索引名(≈MySQL库名)
SIZE = 100
SCROLL = '5m'
DOC_TYPE = '_doc'
# SORT_KEY = '_id'  # 排序key名


class ES:
    def __init__(self, hosts=HOSTS):
        self.es = Elasticsearch(hosts)

    @staticmethod
    def yellow(x):
        print('\033[93m{}\033[0m'.format(x))

    def search(self, body=None, index=INDEX):
        return self.es.search(index, body or {
   'query': {
   'match_all': {
   }}})  # dict

    def scroll(self, body, index=INDEX, size=SIZE, return_ls=False):
        """分批取数"""
        js = self.es.search(index, body, scroll=SCROLL, size=size)
        scroll_id = js['_scroll_id']  # 卷动ID:用于取出剩余数据
        if return_ls:
            yield js['hits']['hits']  # 产出首批数据
            total 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值