最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 操作 ElasticSearch的完整代碼

 更新時(shí)間:2019年08月04日 14:47:08   作者:shaomine  
python提供了操作ElasticSearch 接口,因此要用python來(lái)操作ElasticSearch,這篇文章主要介紹了Python 操作 ElasticSearch,需要的朋友可以參考下

官方文檔:https://elasticsearch-py.readthedocs.io/en/master/

  1、介紹

    python提供了操作ElasticSearch 接口,因此要用python來(lái)操作ElasticSearch,首先要安裝python的ElasticSearch包,用命令pip install elasticsearch安裝或下載安裝:https://pypi.python.org/pypi/elasticsearch/5.4.0

  2、創(chuàng)建索引

    假如創(chuàng)建索引名稱(chēng)為ott,類(lèi)型為ott_type的索引,該索引中有五個(gè)字段:

    title:存儲(chǔ)中文標(biāo)題,

    date:存儲(chǔ)日期格式(2017-09-08),

    keyword:存儲(chǔ)中文關(guān)鍵字,

    source:存儲(chǔ)中文來(lái)源,

    link:存儲(chǔ)鏈接,

    創(chuàng)建映射:

    

    

3、索引數(shù)據(jù)

    

    批量索引

    利用bulk批量索引數(shù)據(jù)

    

  4、查詢索引

     

5、刪除數(shù)據(jù)

    

  6、完整代碼

#coding:utf8
import os
import time
from os import walk
import CSVOP
from datetime import datetime
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
class ElasticObj:
  def __init__(self, index_name,index_type,ip ="127.0.0.1"):
    '''
    :param index_name: 索引名稱(chēng)
    :param index_type: 索引類(lèi)型
    '''
    self.index_name =index_name
    self.index_type = index_type
    # 無(wú)用戶名密碼狀態(tài)
    #self.es = Elasticsearch([ip])
    #用戶名密碼狀態(tài)
    self.es = Elasticsearch([ip],http_auth=('elastic', 'password'),port=9200)
  def create_index(self,index_name="ott",index_type="ott_type"):
    '''
    創(chuàng)建索引,創(chuàng)建索引名稱(chēng)為ott,類(lèi)型為ott_type的索引
    :param ex: Elasticsearch對(duì)象
    :return:
    '''
    #創(chuàng)建映射
    _index_mappings = {
      "mappings": {
        self.index_type: {
          "properties": {
            "title": {
              "type": "text",
              "index": True,
              "analyzer": "ik_max_word",
              "search_analyzer": "ik_max_word"
            },
            "date": {
              "type": "text",
              "index": True
            },
            "keyword": {
              "type": "string",
              "index": "not_analyzed"
            },
            "source": {
              "type": "string",
              "index": "not_analyzed"
            },
            "link": {
              "type": "string",
              "index": "not_analyzed"
            }
          }
        }
      }
    }
    if self.es.indices.exists(index=self.index_name) is not True:
      res = self.es.indices.create(index=self.index_name, body=_index_mappings)
      print res
  def IndexData(self):
    es = Elasticsearch()
    csvdir = 'D:/work/ElasticSearch/exportExcels'
    filenamelist = []
    for (dirpath, dirnames, filenames) in walk(csvdir):
      filenamelist.extend(filenames)
      break
    total = 0
    for file in filenamelist:
      csvfile = csvdir + '/' + file
      self.Index_Data_FromCSV(csvfile,es)
      total += 1
      print total
      time.sleep(10)
  def Index_Data_FromCSV(self,csvfile):
    '''
    從CSV文件中讀取數(shù)據(jù),并存儲(chǔ)到es中
    :param csvfile: csv文件,包括完整路徑
    :return:
    '''
    list = CSVOP.ReadCSV(csvfile)
    index = 0
    doc = {}
    for item in list:
      if index > 1:#第一行是標(biāo)題
        doc['title'] = item[0]
        doc['link'] = item[1]
        doc['date'] = item[2]
        doc['source'] = item[3]
        doc['keyword'] = item[4]
        res = self.es.index(index=self.index_name, doc_type=self.index_type, body=doc)
        print(res['created'])
      index += 1
      print index
  def Index_Data(self):
    '''
    數(shù)據(jù)存儲(chǔ)到es
    :return:
    '''
    list = [
      {  "date": "2017-09-13",
        "source": "慧聰網(wǎng)",
        "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
        "keyword": "電視",
        "title": "付費(fèi) 電視 行業(yè)面臨的轉(zhuǎn)型和挑戰(zhàn)"
       },
      {  "date": "2017-09-13",
        "source": "中國(guó)文明網(wǎng)",
        "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
        "keyword": "電視",
        "title": "電視 專(zhuān)題片《巡視利劍》廣獲好評(píng):鐵腕反腐凝聚黨心民心"
       }
       ]
    for item in list:
      res = self.es.index(index=self.index_name, doc_type=self.index_type, body=item)
      print(res['created'])
  def bulk_Index_Data(self):
    '''
    用bulk將批量數(shù)據(jù)存儲(chǔ)到es
    :return:
    '''
    list = [
      {"date": "2017-09-13",
       "source": "慧聰網(wǎng)",
       "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
       "keyword": "電視",
       "title": "付費(fèi) 電視 行業(yè)面臨的轉(zhuǎn)型和挑戰(zhàn)"
       },
      {"date": "2017-09-13",
       "source": "中國(guó)文明網(wǎng)",
       "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
       "keyword": "電視",
       "title": "電視 專(zhuān)題片《巡視利劍》廣獲好評(píng):鐵腕反腐凝聚黨心民心"
       },
      {"date": "2017-09-13",
       "source": "人民電視",
       "link": "http://tv.people.com.cn/BIG5/n1/2017/0913/c67816-29533981.html",
       "keyword": "電視",
       "title": "中國(guó)第21批赴剛果(金)維和部隊(duì)啟程--人民 電視 --人民網(wǎng)"
       },
      {"date": "2017-09-13",
       "source": "站長(zhǎng)之家",
       "link": "http://www.chinaz.com/news/2017/0913/804263.shtml",
       "keyword": "電視",
       "title": "電視 盒子 哪個(gè)牌子好? 吐血奉獻(xiàn)三大選購(gòu)秘笈"
       }
    ]
    ACTIONS = []
    i = 1
    for line in list:
      action = {
        "_index": self.index_name,
        "_type": self.index_type,
        "_id": i, #_id 也可以默認(rèn)生成,不賦值
        "_source": {
          "date": line['date'],
          "source": line['source'].decode('utf8'),
          "link": line['link'],
          "keyword": line['keyword'].decode('utf8'),
          "title": line['title'].decode('utf8')}
      }
      i += 1
      ACTIONS.append(action)
      # 批量處理
    success, _ = bulk(self.es, ACTIONS, index=self.index_name, raise_on_error=True)
    print('Performed %d actions' % success)
  def Delete_Index_Data(self,id):
    '''
    刪除索引中的一條
    :param id:
    :return:
    '''
    res = self.es.delete(index=self.index_name, doc_type=self.index_type, id=id)
    print res
  def Get_Data_Id(self,id):
    res = self.es.get(index=self.index_name, doc_type=self.index_type,id=id)
    print(res['_source'])
    print '------------------------------------------------------------------'
    #
    # # 輸出查詢到的結(jié)果
    for hit in res['hits']['hits']:
      # print hit['_source']
      print hit['_source']['date'],hit['_source']['source'],hit['_source']['link'],hit['_source']['keyword'],hit['_source']['title']
  def Get_Data_By_Body(self):
    # doc = {'query': {'match_all': {}}}
    doc = {
      "query": {
        "match": {
          "keyword": "電視"
        }
      }
    }
    _searched = self.es.search(index=self.index_name, doc_type=self.index_type, body=doc)
    for hit in _searched['hits']['hits']:
      # print hit['_source']
      print hit['_source']['date'], hit['_source']['source'], hit['_source']['link'], hit['_source']['keyword'], \
      hit['_source']['title']

obj =ElasticObj("ott","ott_type",ip ="47.93.117.127")
# obj = ElasticObj("ott1", "ott_type1")
# obj.create_index()
obj.Index_Data()
# obj.bulk_Index_Data()
# obj.IndexData()
# obj.Delete_Index_Data(1)
# csvfile = 'D:/work/ElasticSearch/exportExcels/2017-08-31_info.csv'
# obj.Index_Data_FromCSV(csvfile)
# obj.GetData(es)

總結(jié)

以上所述是小編給大家介紹的Python 操作 ElasticSearch的完整代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!

相關(guān)文章

  • Python統(tǒng)計(jì)學(xué)一數(shù)據(jù)的概括性度量詳解

    Python統(tǒng)計(jì)學(xué)一數(shù)據(jù)的概括性度量詳解

    這篇文章主要介紹了Python統(tǒng)計(jì)學(xué)一數(shù)據(jù)的概括性度量詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-03-03
  • 關(guān)于pytorch訓(xùn)練分類(lèi)器

    關(guān)于pytorch訓(xùn)練分類(lèi)器

    這篇文章主要介紹了關(guān)于pytorch訓(xùn)練分類(lèi)器問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 詳解Python中的偏函數(shù)(Partial Functions)

    詳解Python中的偏函數(shù)(Partial Functions)

    Python中的偏函數(shù)是來(lái)自函數(shù)式編程的一個(gè)強(qiáng)大工具,它的主要目標(biāo)是減少函數(shù)調(diào)用的復(fù)雜性這個(gè)概念可能起初看起來(lái)有點(diǎn)困難理解,但一旦你明白了它的工作方式,它可能會(huì)成為你的編程工具箱中的重要組成部分,文中有相關(guān)的代碼介紹,需要的朋友可以參考下
    2023-06-06
  • Python的for和break循環(huán)結(jié)構(gòu)中使用else語(yǔ)句的技巧

    Python的for和break循環(huán)結(jié)構(gòu)中使用else語(yǔ)句的技巧

    平時(shí)我們把在if結(jié)構(gòu)中使用else語(yǔ)句當(dāng)作理所當(dāng)然,然而,Python強(qiáng)大的語(yǔ)法糖可以讓else語(yǔ)句在for和while循環(huán)中使用!下面我們就通過(guò)例子來(lái)看一下Python的for和break循環(huán)結(jié)構(gòu)中使用else語(yǔ)句的技巧
    2016-05-05
  • python用plotly實(shí)現(xiàn)繪制局部放大圖

    python用plotly實(shí)現(xiàn)繪制局部放大圖

    大家好,本篇文章主要講的是python用plotly實(shí)現(xiàn)繪制局部放大圖,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下
    2022-02-02
  • 深入理解Python虛擬機(jī)之進(jìn)程、線程和協(xié)程區(qū)別詳解

    深入理解Python虛擬機(jī)之進(jìn)程、線程和協(xié)程區(qū)別詳解

    在本篇文章當(dāng)中深入分析在 Python 當(dāng)中 進(jìn)程、線程和協(xié)程的區(qū)別,這三個(gè)概念會(huì)讓人非常迷惑,如果沒(méi)有深入了解這三者的實(shí)現(xiàn)原理,只是看一些文字說(shuō)明,也很難理解,在本篇文章當(dāng)中我們將通過(guò)分析部分源代碼來(lái)詳細(xì)分析一下這三者根本的區(qū)別是什么,需要的朋友可以參考下
    2023-10-10
  • Python使用列表和字典實(shí)現(xiàn)簡(jiǎn)單的考試系統(tǒng)詳解

    Python使用列表和字典實(shí)現(xiàn)簡(jiǎn)單的考試系統(tǒng)詳解

    這篇文章主要介紹了Python使用列表和字典實(shí)現(xiàn)簡(jiǎn)單的考試系統(tǒng),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧
    2023-01-01
  • python實(shí)戰(zhàn)之Scrapy框架爬蟲(chóng)爬取微博熱搜

    python實(shí)戰(zhàn)之Scrapy框架爬蟲(chóng)爬取微博熱搜

    前面講解了Scrapy中各個(gè)模塊基本使用方法以及代理池、Cookies池。接下來(lái)我們以一個(gè)反爬比較強(qiáng)的網(wǎng)站新浪微博為例,來(lái)實(shí)現(xiàn)一下Scrapy的大規(guī)模爬取。
    2021-09-09
  • Python smtplib實(shí)現(xiàn)發(fā)送郵件功能

    Python smtplib實(shí)現(xiàn)發(fā)送郵件功能

    這篇文章主要為大家詳細(xì)介紹了Python smtplib實(shí)現(xiàn)發(fā)送郵件功能,包含文本、附件、圖片等,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • pycharm內(nèi)無(wú)法import已安裝的模塊問(wèn)題解決

    pycharm內(nèi)無(wú)法import已安裝的模塊問(wèn)題解決

    今天小編就為大家分享一篇pycharm內(nèi)無(wú)法import已安裝的模塊問(wèn)題解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02

最新評(píng)論

昔阳县| 白银市| 汽车| 徐州市| 远安县| 余庆县| 含山县| 青铜峡市| 泽州县| 曲松县| 平罗县| 绵竹市| 阳泉市| 罗定市| 高清| 会宁县| 新泰市| 柘城县| 章丘市| 阳东县| 高平市| 永嘉县| 浦城县| 雷波县| 普安县| 云梦县| 定襄县| 阿坝| 新兴县| 隆昌县| 木兰县| 江孜县| 拉萨市| 盈江县| 阿拉尔市| 南江县| 得荣县| 延寿县| 称多县| 依安县| 吉隆县|