# Python
#实现自定义主键写入,覆盖插入
# -*- 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
```python
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版本需要对应
```python
from elasticsearch5 import Elasticsearch
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
```
# 搜索数据的方法:
```python
# 字典形式设置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()
```
#doc_type
早期版本存在 数据类型 7*以后版本默认即可