Python 操作 ElasticSearch的完整代码


Posted in Python onAugust 04, 2019

官方文档:https://elasticsearch-py.readthedocs.io/en/master/

1、介绍

python提供了操作ElasticSearch 接口,因此要用python来操作ElasticSearch,首先要安装python的ElasticSearch包,用命令pip install elasticsearch安装或下载安装:https://pypi.python.org/pypi/elasticsearch/5.4.0

  2、创建索引

假如创建索引名称为ott,类型为ott_type的索引,该索引中有五个字段:

title:存储中文标题,

date:存储日期格式(2017-09-08),

keyword:存储中文关键字,

source:存储中文来源,

link:存储链接,

创建映射:

Python 操作 ElasticSearch的完整代码

Python 操作 ElasticSearch的完整代码

3、索引数据

Python 操作 ElasticSearch的完整代码

批量索引

利用bulk批量索引数据

Python 操作 ElasticSearch的完整代码

  4、查询索引

Python 操作 ElasticSearch的完整代码 

5、删除数据

Python 操作 ElasticSearch的完整代码

6、完整代码

#coding:utf8
import os
import time
from os import walk
import CSVOP
from datetime import datetime
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
class ElasticObj:
  def __init__(self, index_name,index_type,ip ="127.0.0.1"):
    '''
    :param index_name: 索引名称
    :param index_type: 索引类型
    '''
    self.index_name =index_name
    self.index_type = index_type
    # 无用户名密码状态
    #self.es = Elasticsearch([ip])
    #用户名密码状态
    self.es = Elasticsearch([ip],http_auth=('elastic', 'password'),port=9200)
  def create_index(self,index_name="ott",index_type="ott_type"):
    '''
    创建索引,创建索引名称为ott,类型为ott_type的索引
    :param ex: Elasticsearch对象
    :return:
    '''
    #创建映射
    _index_mappings = {
      "mappings": {
        self.index_type: {
          "properties": {
            "title": {
              "type": "text",
              "index": True,
              "analyzer": "ik_max_word",
              "search_analyzer": "ik_max_word"
            },
            "date": {
              "type": "text",
              "index": True
            },
            "keyword": {
              "type": "string",
              "index": "not_analyzed"
            },
            "source": {
              "type": "string",
              "index": "not_analyzed"
            },
            "link": {
              "type": "string",
              "index": "not_analyzed"
            }
          }
        }
      }
    }
    if self.es.indices.exists(index=self.index_name) is not True:
      res = self.es.indices.create(index=self.index_name, body=_index_mappings)
      print res
  def IndexData(self):
    es = Elasticsearch()
    csvdir = 'D:/work/ElasticSearch/exportExcels'
    filenamelist = []
    for (dirpath, dirnames, filenames) in walk(csvdir):
      filenamelist.extend(filenames)
      break
    total = 0
    for file in filenamelist:
      csvfile = csvdir + '/' + file
      self.Index_Data_FromCSV(csvfile,es)
      total += 1
      print total
      time.sleep(10)
  def Index_Data_FromCSV(self,csvfile):
    '''
    从CSV文件中读取数据,并存储到es中
    :param csvfile: csv文件,包括完整路径
    :return:
    '''
    list = CSVOP.ReadCSV(csvfile)
    index = 0
    doc = {}
    for item in list:
      if index > 1:#第一行是标题
        doc['title'] = item[0]
        doc['link'] = item[1]
        doc['date'] = item[2]
        doc['source'] = item[3]
        doc['keyword'] = item[4]
        res = self.es.index(index=self.index_name, doc_type=self.index_type, body=doc)
        print(res['created'])
      index += 1
      print index
  def Index_Data(self):
    '''
    数据存储到es
    :return:
    '''
    list = [
      {  "date": "2017-09-13",
        "source": "慧聪网",
        "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
        "keyword": "电视",
        "title": "付费 电视 行业面临的转型和挑战"
       },
      {  "date": "2017-09-13",
        "source": "中国文明网",
        "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
        "keyword": "电视",
        "title": "电视 专题片《巡视利剑》广获好评:铁腕反腐凝聚党心民心"
       }
       ]
    for item in list:
      res = self.es.index(index=self.index_name, doc_type=self.index_type, body=item)
      print(res['created'])
  def bulk_Index_Data(self):
    '''
    用bulk将批量数据存储到es
    :return:
    '''
    list = [
      {"date": "2017-09-13",
       "source": "慧聪网",
       "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
       "keyword": "电视",
       "title": "付费 电视 行业面临的转型和挑战"
       },
      {"date": "2017-09-13",
       "source": "中国文明网",
       "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
       "keyword": "电视",
       "title": "电视 专题片《巡视利剑》广获好评:铁腕反腐凝聚党心民心"
       },
      {"date": "2017-09-13",
       "source": "人民电视",
       "link": "http://tv.people.com.cn/BIG5/n1/2017/0913/c67816-29533981.html",
       "keyword": "电视",
       "title": "中国第21批赴刚果(金)维和部?启程--人民 电视 --人民网"
       },
      {"date": "2017-09-13",
       "source": "站长之家",
       "link": "http://www.chinaz.com/news/2017/0913/804263.shtml",
       "keyword": "电视",
       "title": "电视 盒子 哪个牌子好? 吐血奉献三大选购秘笈"
       }
    ]
    ACTIONS = []
    i = 1
    for line in list:
      action = {
        "_index": self.index_name,
        "_type": self.index_type,
        "_id": i, #_id 也可以默认生成,不赋值
        "_source": {
          "date": line['date'],
          "source": line['source'].decode('utf8'),
          "link": line['link'],
          "keyword": line['keyword'].decode('utf8'),
          "title": line['title'].decode('utf8')}
      }
      i += 1
      ACTIONS.append(action)
      # 批量处理
    success, _ = bulk(self.es, ACTIONS, index=self.index_name, raise_on_error=True)
    print('Performed %d actions' % success)
  def Delete_Index_Data(self,id):
    '''
    删除索引中的一条
    :param id:
    :return:
    '''
    res = self.es.delete(index=self.index_name, doc_type=self.index_type, id=id)
    print res
  def Get_Data_Id(self,id):
    res = self.es.get(index=self.index_name, doc_type=self.index_type,id=id)
    print(res['_source'])
    print '------------------------------------------------------------------'
    #
    # # 输出查询到的结果
    for hit in res['hits']['hits']:
      # print hit['_source']
      print hit['_source']['date'],hit['_source']['source'],hit['_source']['link'],hit['_source']['keyword'],hit['_source']['title']
  def Get_Data_By_Body(self):
    # doc = {'query': {'match_all': {}}}
    doc = {
      "query": {
        "match": {
          "keyword": "电视"
        }
      }
    }
    _searched = self.es.search(index=self.index_name, doc_type=self.index_type, body=doc)
    for hit in _searched['hits']['hits']:
      # print hit['_source']
      print hit['_source']['date'], hit['_source']['source'], hit['_source']['link'], hit['_source']['keyword'], \
      hit['_source']['title']

obj =ElasticObj("ott","ott_type",ip ="47.93.117.127")
# obj = ElasticObj("ott1", "ott_type1")
# obj.create_index()
obj.Index_Data()
# obj.bulk_Index_Data()
# obj.IndexData()
# obj.Delete_Index_Data(1)
# csvfile = 'D:/work/ElasticSearch/exportExcels/2017-08-31_info.csv'
# obj.Index_Data_FromCSV(csvfile)
# obj.GetData(es)

总结

以上所述是小编给大家介绍的Python 操作 ElasticSearch的完整代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

Python 相关文章推荐
通过python下载FTP上的文件夹的实现代码
Feb 10 Python
在Django的视图(View)外使用Session的方法
Jul 23 Python
利用Python破解斗地主残局详解
Jun 30 Python
python 自定义对象的打印方法
Jan 12 Python
python实现小球弹跳效果
May 10 Python
实例详解Python模块decimal
Jun 26 Python
详解numpy.meshgrid()方法使用
Aug 01 Python
python类的实例化问题解决
Aug 31 Python
Python列表操作方法详解
Feb 09 Python
Python发送邮件封装实现过程详解
May 09 Python
python 实现表情识别
Nov 21 Python
如何用python开发Zeroc Ice应用
Jan 29 Python
python elasticsearch从创建索引到写入数据的全过程
Aug 04 #Python
elasticsearch python 查询的两种方法
Aug 04 #Python
python Elasticsearch索引建立和数据的上传详解
Aug 04 #Python
Django 创建新App及其常用命令的实现方法
Aug 04 #Python
python模拟鼠标点击和键盘输入的操作
Aug 04 #Python
python PyAutoGUI 模拟鼠标键盘操作和截屏功能
Aug 04 #Python
讲解Python3中NumPy数组寻找特定元素下标的两种方法
Aug 04 #Python
You might like
用PHP调用Oracle存储过程
2006/10/09 PHP
php日历[测试通过]
2008/03/27 PHP
js下利用控制器载入对应脚本
2010/07/17 Javascript
基于jquery的跟随屏幕滚动代码
2012/07/24 Javascript
Validform+layer实现漂亮的表单验证特效
2016/01/17 Javascript
JS动态改变浏览器标题的方法
2016/04/06 Javascript
JavaScript验证知识整理
2017/03/24 Javascript
webpack4+express+mongodb+vue实现增删改查的示例
2018/11/08 Javascript
Postman无法正常返回结果问题解决
2020/08/28 Javascript
Jquery Fade用法详解
2020/11/06 jQuery
nodejs中内置模块fs,path常见的用法说明
2020/11/07 NodeJs
[37:45]2014 DOTA2国际邀请赛中国区预选赛5.21 DT VS Orenda
2014/05/22 DOTA
Python发送以整个文件夹的内容为附件的邮件的教程
2015/05/06 Python
人机交互程序 python实现人机对话
2017/11/14 Python
简单谈谈Python的pycurl模块
2018/04/07 Python
Python设计模式之简单工厂模式实例详解
2019/01/22 Python
opencv实现简单人脸识别
2021/02/19 Python
python单向链表的基本实现与使用方法【定义、遍历、添加、删除、查找等】
2019/10/24 Python
安装多个版本的TensorFlow的方法步骤
2020/04/21 Python
Python中如何引入第三方模块
2020/05/27 Python
keras做CNN的训练误差loss的下降操作
2020/06/22 Python
keras的三种模型实现与区别说明
2020/07/03 Python
css3之UI元素状态伪类选择器实例演示
2017/08/11 HTML / CSS
html5 input输入实时检测以及延时优化
2018/07/18 HTML / CSS
小天鹅官方商城:LittleSwan
2017/06/16 全球购物
请描述一下”is a”关系和”has a”关系
2015/02/03 面试题
行政助理岗位职责范文
2013/12/03 职场文书
农场厂长岗位职责
2013/12/28 职场文书
大学生自我鉴定评语
2014/01/27 职场文书
暑期社会实践方案
2014/02/05 职场文书
法院干警四风问题自我剖析材料
2014/09/29 职场文书
婚礼答谢礼品
2015/01/20 职场文书
董事长开业致辞
2015/07/29 职场文书
高中历史教学反思
2016/02/19 职场文书
六年级作文之自救
2019/12/19 职场文书
Python接口自动化之文件上传/下载接口详解
2022/04/05 Python