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实现排序算法
Feb 14 Python
python里对list中的整数求平均并排序
Sep 12 Python
Python中itertools模块用法详解
Sep 25 Python
详解Python中内置的NotImplemented类型的用法
Mar 31 Python
python通过加号运算符操作列表的方法
Jul 28 Python
pandas数值计算与排序方法
Apr 12 Python
python抽取指定url页面的title方法
May 11 Python
Python单元测试简单示例
Jul 03 Python
python使用requests模块实现爬取电影天堂最新电影信息
Apr 03 Python
python将图片转base64,实现前端显示
Jan 09 Python
使用TensorFlow搭建一个全连接神经网络教程
Feb 06 Python
keras slice layer 层实现方式
Jun 11 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全局变量与超级全局变量区别分析
2016/04/01 PHP
php基于jquery的ajax技术传递json数据简单实例
2016/04/15 PHP
浅析php-fpm静态和动态执行方式的比较
2016/11/09 PHP
PHP进阶学习之类的自动加载机制原理分析
2019/06/18 PHP
JavaScript Undefined,Null类型和NaN值区别
2008/10/22 Javascript
Jquery Select操作方法集合脚本之家特别版
2010/05/17 Javascript
jQuery在IE下使用未闭合的xml代码创建元素时的Bug介绍
2012/01/10 Javascript
js自动闭合html标签(自动补全html标记)
2012/10/04 Javascript
Node.js中使用事件发射器模式实现事件绑定详解
2014/08/15 Javascript
JavaScript对Json的增删改属性详解
2016/06/02 Javascript
微信小程序 animation API详解及实例代码
2016/10/08 Javascript
javascript学习之json入门
2016/12/22 Javascript
微信小程序 开发MAP(地图)实例详解
2017/06/27 Javascript
jQuery实现的电子时钟效果完整示例
2018/04/28 jQuery
js正则表达式校验指定字符串的方法
2018/07/23 Javascript
element ui table 增加筛选的方法示例
2018/11/02 Javascript
react实现同页面三级跳转路由布局
2019/09/26 Javascript
Vue的click事件防抖和节流处理详解
2019/11/13 Javascript
[52:52]DOTA2上海特级锦标赛C组资格赛#1 OG VS LGD第三局
2016/02/27 DOTA
Python标准模块--ContextManager上下文管理器的具体用法
2017/11/27 Python
pygame游戏之旅 添加碰撞效果的方法
2018/11/20 Python
python之yield和Generator深入解析
2019/09/18 Python
Linux安装Python3如何和系统自带的Python2并存
2020/07/23 Python
VSCODE配置Markdown及Markdown基础语法详解
2021/01/19 Python
基于PyTorch中view的用法说明
2021/03/03 Python
CSS3中文字镂空、透明值、阴影效果设置示例小结
2016/03/07 HTML / CSS
纽约和芝加哥当天送花:Ode à la Rose
2019/07/05 全球购物
阿里巴巴Oracle DBA笔试题答案-备份恢复类
2013/11/20 面试题
初一体育教学反思
2014/01/29 职场文书
小班评语大全
2014/05/04 职场文书
2015小学教师年度工作总结
2015/05/12 职场文书
幼儿园六一儿童节主持词
2015/06/30 职场文书
初中班主任工作随笔
2015/08/15 职场文书
如何用JavaScipt测网速
2021/05/09 Javascript
解决Python保存文件名太长OSError: [Errno 36] File name too long
2022/05/11 Python
详解flex:1什么意思
2022/07/23 HTML / CSS