ES相关操作

# coding: utf-8
import time

import xlrd
from elasticsearch import Elasticsearch

_index = 'school'
_type = 'name'
es_url = '127.0.0.1'
es = Elasticsearch(es_url)


def bulk_es(chunk_data):
    response = es.index(_index, _type, chunk_data)
    print(response['result'])
    print(response['_shards'])


def index_bulk():
    # 批量索引school.json中的数据
    with open('school.json', encoding='utf-8') as f:
        schools = eval(f.read())
        for index, school in enumerate(schools):
            print('index=%s' % str(index))
            # bulk_es(school)


def index():
    # 单个创建索引数据
    school = {
        "c_name": "普莱斯伍德基督学院",
        "e_name": "Prestonwood Christian Academy",
        "country": "美国",
        "education": "高中"
    }
    # response = es.index('school', 'name', school)
    # print(response['result'])
    # print(response['_shards'])

    # results = es.search('school', 'name', {'query': {'match': {'c_name': '阿德莱德大学'}}}, size=10)
    results = es.search('school', 'name', {'query': {'match_all': {}}}, size=1000)
    hello = [{'id': data['_id'], 'index': data['_index'], 'type': data['_type'], 'source': data['_source']} for data in
             results['hits']['hits']]
    print(hello)


def delete():
    # resp = es.delete(index='school', doc_type='name', id='Xs7qJmgBxSbyj5YMlBWk')
    query = {'query': {"match_all": {}}}
    resp = es.delete_by_query(index='school', doc_type='name', body=query)
    print(resp)


def read_excel():
	# 表格读操作以及ES服务器存操作
    workbook = xlrd.open_workbook(r'school.xls')
    sheet2 = workbook.sheet_by_name('Sheet1')

    # 获取整行和整列的值(数组)
    for i in range(1, 218):
        rows = sheet2.row_values(i)  # 获取第四行内容
        print(rows)
        school = dict()
        school['c_name'], school['e_name'], school['country'] = rows[2].strip(), rows[3].strip(), rows[1].strip()
        print(school)
        response = es.index('school', 'name', school)
        print(response['result'])
        print(response['_shards'])


if __name__ == "__main__":
    index()
    # delete()
    # read_excel()

你可能感兴趣的:(ES相关操作)