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 相关文章推荐
Python实现LRU算法的2种方法
Jun 24 Python
利用Python破解斗地主残局详解
Jun 30 Python
利用python如何处理nc数据详解
May 23 Python
Opencv+Python 色彩通道拆分及合并的示例
Dec 08 Python
Python3 pip3 list 出现 DEPRECATION 警告的解决方法
Feb 16 Python
Python中函数的基本定义与调用及内置函数详解
May 13 Python
python处理document文档保留原样式
Sep 23 Python
Python 导入文件过程图解
Oct 15 Python
python wav模块获取采样率 采样点声道量化位数(实例代码)
Jan 22 Python
python利用opencv实现SIFT特征提取与匹配
Mar 05 Python
Python 炫技操作之合并字典的七种方法
Apr 10 Python
解决keras使用cov1D函数的输入问题
Jun 29 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
web目录下不应该存在多余的程序(安全考虑)
2012/05/09 PHP
ThinkPHP实现简单登陆功能
2017/04/28 PHP
在IE中调用javascript打开Excel的代码(downmoon原作)
2007/04/02 Javascript
javascript 面向对象编程基础:继承
2009/08/21 Javascript
鼠标焦点离开文本框时验证的js代码
2013/07/19 Javascript
node.js中的fs.rename方法使用说明
2014/12/16 Javascript
原生JS实现旋转木马式图片轮播插件
2016/04/25 Javascript
JS基于正则截取替换特定字符之间字符串操作示例
2017/02/03 Javascript
Vue filters过滤器的使用方法
2017/07/14 Javascript
前端主流框架vue学习笔记第一篇
2017/07/26 Javascript
五步轻松实现zTree的使用
2017/11/01 Javascript
vue2.0实现列表数据增加和删除
2020/06/17 Javascript
antd vue 刷新保留当前页面路由,保留选中菜单,保留menu选中操作
2020/08/06 Javascript
JavaScript array常用方法代码实例详解
2020/09/02 Javascript
Python中操作文件之write()方法的使用教程
2015/05/25 Python
Python 模拟登陆的两种实现方法
2017/08/10 Python
Python爬取附近餐馆信息代码示例
2017/12/09 Python
Python实现随机生成手机号及正则验证手机号的方法
2018/04/25 Python
python中itertools模块zip_longest函数详解
2018/06/12 Python
python中类的属性和方法介绍
2018/11/27 Python
python使用Paramiko模块实现远程文件拷贝
2019/04/30 Python
Windows下PyCharm2018.3.2 安装教程(图文详解)
2019/10/24 Python
linux 下python多线程递归复制文件夹及文件夹中的文件
2020/01/02 Python
python获取整个网页源码的方法
2020/08/03 Python
python使用建议与技巧分享(二)
2020/08/17 Python
Python描述数据结构学习之哈夫曼树篇
2020/09/07 Python
美国电视购物:QVC
2017/02/06 全球购物
Nike瑞士官网:Nike CH
2021/01/18 全球购物
构造方法和其他方法的区别
2016/04/26 面试题
好的自荐信包括什么内容
2013/11/07 职场文书
节约电力资源的建议书
2014/03/12 职场文书
2014年预备党员学习两会心得体会
2014/03/17 职场文书
安全责任协议书
2014/04/21 职场文书
竞选班长演讲稿500字
2014/08/22 职场文书
Pandas实现DataFrame的简单运算、统计与排序
2022/03/31 Python
Java8 Stream API 提供了一种高效且易于使用的处理数据的方式
2022/04/13 Java/Android