欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 操作 ElasticSearch的完整代碼

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

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

  1、介紹

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

  2、創(chuàng)建索引

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

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

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

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

    source:存儲中文來源,

    link:存儲鏈接,

    創(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: 索引名稱
    :param index_type: 索引類型
    '''
    self.index_name =index_name
    self.index_type = index_type
    # 無用戶名密碼狀態(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)建索引名稱為ott,類型為ott_type的索引
    :param ex: Elasticsearch對象
    :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ù),并存儲到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ù)存儲到es
    :return:
    '''
    list = [
      {  "date": "2017-09-13",
        "source": "慧聰網(wǎng)",
        "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
        "keyword": "電視",
        "title": "付費 電視 行業(yè)面臨的轉(zhuǎn)型和挑戰(zhàn)"
       },
      {  "date": "2017-09-13",
        "source": "中國文明網(wǎng)",
        "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
        "keyword": "電視",
        "title": "電視 專題片《巡視利劍》廣獲好評:鐵腕反腐凝聚黨心民心"
       }
       ]
    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ù)存儲到es
    :return:
    '''
    list = [
      {"date": "2017-09-13",
       "source": "慧聰網(wǎng)",
       "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
       "keyword": "電視",
       "title": "付費 電視 行業(yè)面臨的轉(zhuǎn)型和挑戰(zhàn)"
       },
      {"date": "2017-09-13",
       "source": "中國文明網(wǎng)",
       "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
       "keyword": "電視",
       "title": "電視 專題片《巡視利劍》廣獲好評:鐵腕反腐凝聚黨心民心"
       },
      {"date": "2017-09-13",
       "source": "人民電視",
       "link": "http://tv.people.com.cn/BIG5/n1/2017/0913/c67816-29533981.html",
       "keyword": "電視",
       "title": "中國第21批赴剛果(金)維和部隊啟程--人民 電視 --人民網(wǎng)"
       },
      {"date": "2017-09-13",
       "source": "站長之家",
       "link": "http://www.chinaz.com/news/2017/0913/804263.shtml",
       "keyword": "電視",
       "title": "電視 盒子 哪個牌子好? 吐血奉獻三大選購秘笈"
       }
    ]
    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的完整代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!

相關(guān)文章

  • Pytorch之?dāng)U充tensor的操作

    Pytorch之?dāng)U充tensor的操作

    這篇文章主要介紹了Pytorch之?dāng)U充tensor的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • 人臉檢測實戰(zhàn)終極之OpenCV+Python實現(xiàn)人臉對齊

    人臉檢測實戰(zhàn)終極之OpenCV+Python實現(xiàn)人臉對齊

    這篇文章主要是為了演示如何使用 OpenCV、Python 和面部標(biāo)志從而實現(xiàn)對齊人臉。文中示例代碼對我們的工作或?qū)W習(xí)有一定的幫助,感興趣的小伙伴可以學(xué)習(xí)一下
    2021-12-12
  • Python進階-函數(shù)默認(rèn)參數(shù)(詳解)

    Python進階-函數(shù)默認(rèn)參數(shù)(詳解)

    下面小編就為大家?guī)硪黄狿ython進階-函數(shù)默認(rèn)參數(shù)(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • 如何利用python和DOS獲取wifi密碼

    如何利用python和DOS獲取wifi密碼

    這篇文章主要介紹了如何利用python和DOS獲取wifi密碼,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-03-03
  • 利用python查看官方文檔

    利用python查看官方文檔

    這篇文章主要介紹了利用python查看官方文檔,我們在學(xué)習(xí)和工作中,總是會遇到一些問題,或許官方文檔能解決這一問題,下面我們就來看看python如何查看官方文檔吧
    2022-01-01
  • OpenCV物體跟蹤樹莓派視覺小車實現(xiàn)過程學(xué)習(xí)

    OpenCV物體跟蹤樹莓派視覺小車實現(xiàn)過程學(xué)習(xí)

    這篇文章主要介紹了OpenCV物體跟蹤樹莓派視覺小車的實現(xiàn)過程學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2021-10-10
  • 淺談python socket函數(shù)中,send與sendall的區(qū)別與使用方法

    淺談python socket函數(shù)中,send與sendall的區(qū)別與使用方法

    下面小編就為大家?guī)硪黄獪\談python socket函數(shù)中,send與sendall的區(qū)別與使用方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • Python用內(nèi)置模塊來構(gòu)建REST服務(wù)與RPC服務(wù)實戰(zhàn)

    Python用內(nèi)置模塊來構(gòu)建REST服務(wù)與RPC服務(wù)實戰(zhàn)

    這篇文章主要介紹了Python用內(nèi)置模塊來構(gòu)建REST服務(wù)與RPC服務(wù)實戰(zhàn),python在網(wǎng)絡(luò)方面封裝一些內(nèi)置模塊,可以用很簡潔的代碼實現(xiàn)端到端的通信,比如HTTP、RPC服務(wù),下文實戰(zhàn)詳情,需要的朋友可以參考一下
    2022-09-09
  • 在類Unix系統(tǒng)上開始Python3編程入門

    在類Unix系統(tǒng)上開始Python3編程入門

    這篇文章主要介紹了在類Unix系統(tǒng)上開始Python3編程入門,講解了最基礎(chǔ)最直觀的利用Print函數(shù)進行各種輸出的方法,需要的朋友可以參考下
    2015-08-08
  • Pytorch中TensorDataset與DataLoader的使用方式

    Pytorch中TensorDataset與DataLoader的使用方式

    這篇文章主要介紹了Pytorch中TensorDataset與DataLoader的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09

最新評論