Python插入Elasticsearch操作方法解析
作者:cknds 时间:2021-08-30 01:47:09
这篇文章主要介绍了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,
}
来源:https://www.cnblogs.com/yoyowin/p/12209706.html
标签:python,插入,Elasticsearch
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python 爬虫出现403禁止访问错误详解
2023-11-13 06:53:24
php flv视频时间获取函数
2023-09-04 13:41:48
pygame外星人入侵小游戏超详细开发流程
2021-06-15 05:15:47
![](https://img.aspxhome.com/file/2023/9/75909_0s.png)
select 终极美化
2007-10-16 17:57:00
Python爬虫HTPP请求方法有哪些
2023-07-25 16:55:06
Python configparser模块应用过程解析
2022-08-03 19:56:11
Python Django view 两种return的实现方式
2022-05-03 16:07:04
JavaScript Date()在页面内显示日期
2008-02-05 10:18:00
通过python检测字符串的字母
2023-01-11 22:49:47
一个完美网站的101项指标.第四部分.设计
2008-02-29 22:22:00
python处理列表的部分元素的实例详解
2021-04-16 01:13:05
Linux下用Python脚本监控目录变化代码分享
2021-03-30 20:15:59
破解加密的网页代码方法
2010-03-16 12:35:00
Python数据分析库pandas基本操作方法
2022-07-17 23:15:18
![](https://img.aspxhome.com/file/2023/5/88975_0s.jpg)
关于利用:first-letter实现首字下沉的一些看法
2010-04-20 17:19:00
![](https://img.aspxhome.com/file/UploadPic/20104/20/first-letter_no_float-38s.png)
在asp中使用js的encodeURIComponent方法
2012-11-30 20:05:53
W3C优质网页小贴士(一)
2008-04-06 16:35:00
![](https://img.aspxhome.com/file/UploadPic/up/2008040712541063.gif)
在django模板中实现超链接配置
2023-03-03 12:22:44
自动完成autoComplete
2011-01-17 18:01:00
Scrapy元素选择器Xpath用法汇总
2021-09-11 11:42:58