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字典序问题实例
Sep 26 Python
在Python中操作文件之read()方法的使用教程
May 24 Python
web.py 十分钟创建简易博客实现代码
Apr 22 Python
Python简单删除列表中相同元素的方法示例
Jun 12 Python
python生成excel的实例代码
Nov 08 Python
python实现跨excel的工作表sheet之间的复制方法
May 03 Python
Python实现的爬虫刷回复功能示例
Jun 07 Python
对python中if语句的真假判断实例详解
Feb 18 Python
Python 获取指定文件夹下的目录和文件的实现
Aug 30 Python
python实现静态服务器
Sep 05 Python
python实现将字符串中的数字提取出来然后求和
Apr 02 Python
Python类class参数self原理解析
Nov 19 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文档更新介绍
2011/07/22 PHP
帝国cms常用标签汇总
2015/07/06 PHP
ThinkPhP+Apache+PHPstorm整合框架流程图解
2020/11/23 PHP
JQuery 实现的页面滚动时浮动窗口控件
2009/07/10 Javascript
jQuery select操作控制方法小结
2010/05/26 Javascript
浅谈JavaScript函数参数的可修改性问题
2013/12/05 Javascript
JS实现超简单的仿QQ折叠菜单效果
2015/09/21 Javascript
JavaScript控制浏览器全屏及各种浏览器全屏模式的方法、属性和事件
2015/12/20 Javascript
js如何准确获取当前页面url网址信息
2020/09/13 Javascript
window.close(); 关闭浏览器窗口js代码的总结介绍
2016/07/14 Javascript
angular源码学习第一篇 setupModuleLoader方法
2016/10/20 Javascript
微信小程序 详解页面跳转与返回并回传数据
2017/02/13 Javascript
jQuery日程管理控件glDatePicker用法详解
2017/03/29 jQuery
Vue中Axios从远程/后台读取数据
2019/01/21 Javascript
jQuery实现的鼠标拖动画矩形框示例【可兼容IE8】
2019/05/17 jQuery
JS实现可切换图片的幻灯切换效果示例
2019/05/24 Javascript
详解实现vue的数据响应式原理
2021/01/20 Vue.js
浅谈Scrapy框架普通反爬虫机制的应对策略
2017/12/28 Python
Python实现PS图像明亮度调整效果示例
2018/01/23 Python
matplotlib 纵坐标轴显示数据值的实例
2018/05/25 Python
pytorch绘制并显示loss曲线和acc曲线,LeNet5识别图像准确率
2020/01/02 Python
python+adb+monkey实现Rom稳定性测试详解
2020/04/23 Python
scrapy在python爬虫中搭建出错的解决方法
2020/11/22 Python
如何用 Python 制作 GitHub 消息助手
2021/02/20 Python
使用CSS3的ruby-position固定注音位置的用法示例
2016/07/05 HTML / CSS
The Beach People美国:澳洲海滨奢华品牌
2018/07/05 全球购物
英国第一独立滑雪板商店:The Snowboard Asylum
2020/01/16 全球购物
美国工业用品采购网站:Zoro.com
2020/10/27 全球购物
教师实习自我鉴定
2013/12/14 职场文书
国庆节文艺活动方案
2014/02/03 职场文书
爸爸的花儿落了教学反思
2014/02/20 职场文书
员工工作表现评语
2014/04/26 职场文书
学院党委班子四风问题自查报告及整改措施
2014/10/25 职场文书
2015年乡镇残联工作总结
2015/05/13 职场文书
2015年食品安全工作总结
2015/05/15 职场文书
Python Pandas数据分析之iloc和loc的用法详解
2021/11/11 Python