Python插入Elasticsearch操作方法解析
這篇文章主要介紹了Python插入Elasticsearch操作方法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
在用scrapy做爬蟲的時候,需要將數(shù)據(jù)存入的es中。網(wǎng)上找了兩種方法,照葫蘆畫瓢也能出來,暫記下來:
首先安裝了es,版本是5.6.1的較早版本
用pip安裝與es版本相對的es相關(guān)包
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版本需要對應(yīng) 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
以上方法能將數(shù)據(jù)寫入es,但是如果重復(fù)爬取的話,會重復(fù)插入數(shù)據(jù),因為 主鍵 ”_id” 是ES自己產(chǎn)生的,找不到自定義_id的入口。于是放棄。
方法二:實現(xiàn)自定義主鍵寫入,覆蓋插入
# -*- 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版本需要對應(yīng) class SinafinancespiderESPipeline(): def __init__(self): self.ES = ['192.168.52.138:9200'] # 創(chuàng)建es客戶端 self.es = Elasticsearch( self.ES, # 啟動前嗅探es集群服務(wù)器 sniff_on_start=True, # es集群服務(wù)器結(jié)點連接異常時是否刷新es結(jié)點信息 sniff_on_connection_fail=True, # 每60秒刷新節(jié)點信息 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
搜索數(shù)據(jù)的方法:
# 字典形式設(shè)置body query = { 'query': { 'bool': { 'must': [ {'match': {'_all': 'python web'}} ], 'filter': [ {'term': {'status': 2}} ] } } } ret = es.search(index='articles', doc_type='article', body=query) # 查詢數(shù)據(jù) 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, }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pyspark連接mysql數(shù)據(jù)庫報錯的解決
本文主要介紹了pyspark連接mysql數(shù)據(jù)庫報錯的解決,因為spark中缺少連接MySQL的驅(qū)動程序,下面就來介紹一下解決方法,感興趣的可以了解一下2023-11-11python中24小時制轉(zhuǎn)換為12小時制的方法
最近需要實現(xiàn)一個需求,求用戶輸入24小時制的時間,然后顯示12小時制的時間。具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06python基于socket進行端口轉(zhuǎn)發(fā)實現(xiàn)后門隱藏的示例
今天小編就為大家分享一篇python基于socket進行端口轉(zhuǎn)發(fā)實現(xiàn)后門隱藏的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07python語法學(xué)習(xí)之super(),繼承與派生
這篇文章主要介紹了python語法學(xué)習(xí)之super(),繼承與派生,繼承是一種創(chuàng)建新類的方式,具體的super()派生的相關(guān)詳細內(nèi)容需要的小伙伴可以參考下面文章內(nèi)容2022-05-05Python中導(dǎo)入自定義模塊的幾種方法總結(jié)
這篇文章主要介紹了Python中導(dǎo)入自定義模塊的幾種方法總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01Python getattr()函數(shù)使用方法代碼實例
這篇文章主要介紹了Python getattr()函數(shù)使用方法代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08正確理解python中的關(guān)鍵字“with”與上下文管理器
這篇文章主要介紹了關(guān)于python中關(guān)鍵字"with"和上下文管理器的相關(guān)資料,文中介紹的非常詳細,相信對大家學(xué)習(xí)或者使用python具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-04-04