Python插入Elasticsearch操作方法解析


Posted in Python onJanuary 19, 2020

这篇文章主要介绍了Python插入Elasticsearch操作方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

在用scrapy做爬虫的时候,需要将数据存入的es中。网上找了两种方法,照葫芦画瓢也能出来,暂记下来:

首先安装了es,版本是5.6.1的较早版本

用pip安装与es版本相对的es相关包

pip install elasticsearch-dsl==5.1.0

方法一:

以下是pipelines.py模块的完整代码

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import chardet

class SinafinancespiderPipeline(object):
  def process_item(self, item, spider):
    return item


# 写入到es中,需要在settings中启用这个类 ExchangeratespiderESPipeline
# 需要安装pip install elasticsearch-dsl==5.1.0 注意与es版本需要对应
from elasticsearch_dsl import Date,Nested,Boolean,analyzer,Completion,Keyword,Text,Integer,DocType
from elasticsearch_dsl.connections import connections
connections.create_connection(hosts=['192.168.52.138'])
from elasticsearch import Elasticsearch
es = Elasticsearch()

class AticleType(DocType):
  page_from = Keyword()
  # domain报错
  domain=Keyword()
  cra_url=Keyword()
  spider = Keyword()
  cra_time = Keyword()
  page_release_time = Keyword()
  page_title = Text(analyzer="ik_max_word")
  page_content = Text(analyzer="ik_max_word")
class Meta:
    index = "scrapy"
    doc_type = "sinafinance"
    # 以下settings和mappings都没起作用,暂且记下
    settings = {
      "number_of_shards": 3,
    }
    mappings = {
      '_id':{'path':'cra_url'}
    }


class ExchangeratespiderESPipeline(DocType):
  from elasticsearch5 import Elasticsearch
  ES = ['192.168.52.138:9200']
  es = Elasticsearch(ES,sniff_on_start=True)

  def process_item(self, item, spider):

    spider.logger.info("-----enter into insert ES")
    article = AticleType()

    article.page_from=item['page_from']
    article.domain=item['domain']
    article.cra_url =item['cra_url']
    article.spider =item['spider']
    article.cra_time =item['cra_time']
    article.page_release_time =item['page_release_time']
    article.page_title =item['page_title']
    article.page_content =item['page_content']

    article.save()
    return item

以上方法能将数据写入es,但是如果重复爬取的话,会重复插入数据,因为 主键 ”_id” 是ES自己产生的,找不到自定义_id的入口。于是放弃。

方法二:实现自定义主键写入,覆盖插入

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from elasticsearch5 import Elasticsearch

class SinafinancespiderPipeline(object):
  def process_item(self, item, spider):
    return item


# 写入到es中,需要在settings中启用这个类 ExchangeratespiderESPipeline
# 需要安装pip install elasticsearch-dsl==5.1.0 注意与es版本需要对应
class SinafinancespiderESPipeline():
  def __init__(self):
    self.ES = ['192.168.52.138:9200']
    # 创建es客户端
    self.es = Elasticsearch(
      self.ES,
      # 启动前嗅探es集群服务器
      sniff_on_start=True,
      # es集群服务器结点连接异常时是否刷新es结点信息
      sniff_on_connection_fail=True,
      # 每60秒刷新节点信息
      sniffer_timeout=60
    )

  def process_item(self, item, spider):
    spider.logger.info("-----enter into insert ES")
    doc = {
      'page_from': item['page_from'],
      'domain': item['domain'],
      'spider': item['spider'],
      'page_release_time': item['page_release_time'],
      'page_title': item['page_title'],
      'page_content': item['page_content'],
      'cra_url': item['cra_url'],
      'cra_time': item['cra_time']
    }
    self.es.index(index='scrapy', doc_type='sinafinance', body=doc, id=item['cra_url'])

    return item

搜索数据的方法:

# 字典形式设置body
query = {
 'query': {
  'bool': {
   'must': [
    {'match': {'_all': 'python web'}}
   ],
   'filter': [
    {'term': {'status': 2}}
   ]
  }
 }
}
ret = es.search(index='articles', doc_type='article', body=query)

# 查询数据
data = es.search(index='articles', doc_type='article', body=body)
print(data)
# 增加
es.index(...)
# 修改
es.update(...)
# 删除
es.delete()

完成后

在settings.py模块中注册自定义的类

ITEM_PIPELINES = {
  # 'sinafinancespider.pipelines.SinafinancespiderPipeline': 300,
  'sinafinancespider.pipelines.SinafinancespiderESPipeline': 300,
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python3批量删除豆瓣分组下的好友的实现代码
Jun 07 Python
Python抓取手机号归属地信息示例代码
Nov 28 Python
python爬虫之自动登录与验证码识别
Jun 15 Python
Python中dict和set的用法讲解
Mar 28 Python
Python叠加两幅栅格图像的实现方法
Jul 05 Python
python OpenCV GrabCut使用实例解析
Nov 11 Python
用Python画小女孩放风筝的示例
Nov 23 Python
Python如何把十进制数转换成ip地址
May 25 Python
Python定时任务框架APScheduler原理及常用代码
Oct 05 Python
OpenCV实现机器人对物体进行移动跟随的方法实例
Nov 09 Python
python多线程和多进程关系详解
Dec 14 Python
Python实现Excel自动分组合并单元格
Feb 22 Python
Docker部署Python爬虫项目的方法步骤
Jan 19 #Python
Python Selenium参数配置方法解析
Jan 19 #Python
浅谈tensorflow中张量的提取值和赋值
Jan 19 #Python
python通过安装itchat包实现微信自动回复收到的春节祝福
Jan 19 #Python
使用 Python 处理3万多条数据只要几秒钟
Jan 19 #Python
Python openpyxl模块原理及用法解析
Jan 19 #Python
Python imutils 填充图片周边为黑色的实现
Jan 19 #Python
You might like
一个简单的PHP&MYSQL留言板源码
2020/07/19 PHP
关于PHPDocument 代码注释规范的总结
2013/06/25 PHP
Codeigniter控制器controller继承问题实例分析
2016/01/19 PHP
Yii开启片段缓存的方法
2016/03/28 PHP
Yii核心验证器api详解
2016/11/23 PHP
关于JavaScript的面向对象和继承有利新手学习
2013/01/11 Javascript
Json字符串转换为JS对象的高效方法实例
2013/05/01 Javascript
javascript中encodeURI和decodeURI方法使用介绍
2013/05/06 Javascript
怎么清空javascript数组
2013/05/11 Javascript
jQuery插件DataTable使用方法详解(.Net平台)
2016/12/22 Javascript
Mongoose学习全面理解(推荐)
2017/01/21 Javascript
ES6中Math对象新增的方法实例详解
2017/04/25 Javascript
Vue 2中ref属性的使用方法及注意事项
2017/06/12 Javascript
详解webpack和webpack-simple中如何引入css文件
2017/06/28 Javascript
js学习心得_一个简单的动画库封装tween.js
2017/07/14 Javascript
详解AngularJS1.x学习directive 中‘& ’‘=’ ‘@’符号的区别使用
2017/08/23 Javascript
JS二分查找算法详解
2017/11/01 Javascript
利用Vue2.x开发实现JSON树的方法
2018/01/04 Javascript
解决Vue.js父组件$on无法监听子组件$emit触发事件的问题
2018/09/12 Javascript
关于layui 下拉列表的change事件详解
2019/09/20 Javascript
[26:52]LGD vs EG 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/18 DOTA
Python将图片转换为字符画的方法
2020/06/16 Python
django 开发忘记密码通过邮箱找回功能示例
2018/04/17 Python
python 字典 按key值大小 倒序取值的实例
2018/07/06 Python
Python values()与itervalues()的用法详解
2019/11/27 Python
python实现在内存中读写str和二进制数据代码
2020/04/24 Python
如何通过Python实现RabbitMQ延迟队列
2020/11/28 Python
css3 按钮 利用css3实现超酷下载按钮
2013/03/18 HTML / CSS
简单聊聊H5的pushState与replaceState的用法
2018/04/03 HTML / CSS
美国眼镜网:GlassesUSA
2017/09/07 全球购物
递归实现回文判断(如:abcdedbca就是回文,判断一个面试者对递归理解的简单程序)
2013/04/28 面试题
《永远的白衣战士》教学反思
2014/04/25 职场文书
原生JS封装vue Tab切换效果
2021/04/28 Vue.js
Oracle更换为MySQL遇到的问题及解决
2021/05/21 Oracle
Spring Data JPA框架的核心概念和Repository接口
2022/04/28 Java/Android
Windows server 2003卸载和安装IIS的图文教程
2022/07/15 Servers