Python學習筆記-ElasticSearch操作

安裝:pip install -U elasticsearch  (Successfully installed elasticsearch-7.0.3)

ElasticSearch版本:elasticsearch-7.3.0

Python操作代碼如下

# -*- coding:utf-8 -*-

import os
import sys
from elasticsearch import Elasticsearch

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

es = Elasticsearch([{'host': '192.168.0.1', 'port': 19201}], timeout=3600)

netease_news_mapping = {
    'properties': {
        "id": {
            "type": "keyword"
        },
        "url": {
            "type": "keyword"
        },
        "title": {
            "analyzer": "ik_smart",
            "type": "text"
        },
        "content": {
            "analyzer": "ik_smart",
            "type": "text"
        },
        "create_time": {
            "type": "text"
        },
        "type": {
            "type": "keyword"
        }
    }
}


def create_index_and_mapping():
    es.indices.delete(index='netease_news_v1', ignore=[400, 404])
    es.indices.create(index='netease_news_v1', ignore=400)
    es.indices.put_mapping(index='netease_news_v1', doc_type='news', body=netease_news_mapping, include_type_name=True)
    es.indices.put_alias(index='netease_news_v1', name='netease_news')

    es.indices.delete(index='netease_news_v2', ignore=[400, 404])
    es.indices.create(index='netease_news_v2', ignore=400)
    netease_news_mapping_file = os.path.abspath(os.getcwd() + os.sep + 'mapping' + os.sep + 'netease_news.json')
    with open(netease_news_mapping_file, 'rb') as mf:
        lines = mf.readlines()
    es.indices.put_mapping(index='netease_news_v2', doc_type='news', body=(''.join(lines)), include_type_name=True)
    es.indices.put_alias(index='netease_news_v2', name='netease_news')


def create_index_type_data():
    body = {
        "url": "http://gz.news.163.com/19/0822/17/EN700FN104108DGB.html",
        "title": "智能機器人爲人類“分憂” 專利助推行業創新發展",
        "content": "人工巡檢不能抵達?頻率太低?讓智能機器人出馬!\n在貴州,隨着科技部FAST“智能機器人”重點定向專項的啓動申報,中國天眼的運維將迎來一個智能化時代,爲保障其有效觀測時間提供重要技術支撐,將在很大程度上提高中國天眼的運行及維護效率,讓其“多出成果、出好成果、出大成果”。在青島,通過身穿“黃衣”的水下機器人在渾濁水域拍攝的清晰視頻,記者可以看到青島羅博飛海洋物聯網系統傳回的榮成等地的養殖畫面和生態數據。\n機器人被譽爲“製造業皇冠上的明珠”。“人工智能”2017年第一次進入政府工作報告,今年已經是第三年出現在政府工作報告之中。今年的政府工作報告將“人工智能”升級爲“智能+”,提出要打造工業互聯網平臺,拓展“智能+”,爲製造業轉型升級賦能。\n《中國機器人產業發展報告2018》顯示,過去6年我國機器人市場平均增長率接近30%。2018年國內機器人市場規模預計達到87.4億美元,約佔全球1/3。在工業4.0與中國智造的變革浪潮中,一批以智能製造、智慧服務爲使命與願景的機器人企業競相涌現。\n在廣東,截至2018年,廣東省機器人及相關配套產業產值600億元,自主品牌工業機器人產量超過3.2萬臺套,佔全國22%。服務機器人產量超200萬臺套,佔全球四分之一。\n\n機器人產業快速發展,如何保護知識產權成爲各個企業關注的重點。在安徽蕪湖機器人產業園,隨着企業的不斷入駐,專利申請量超過3000件。\n據蕪湖機器人產業園相關負責人介紹,相較於國內其他機器人園區,蕪湖機器人產業園專利申請量最多,發明專利申請佔比最高。機器人企業集羣範圍廣,既有整機企業集羣,也有關鍵零部件企業集羣和系統集成企業集羣,專利技術分佈涉及機器人制造的各個方向。\n在專利的保駕護航下,埃夫特、酷哇等企業快速發展,在國內機器人行業佔據一席之地。\n作爲較早入駐蕪湖機器人產業園的一家企業,埃夫特通過兼併、引進和吸收海外機器人領域的先進技術和經驗,在機器人噴塗、系統集成、運動控制器、下游產業鏈領域迅速躋身世界先進水平,形成從核心零部件到機器人整機再到高端系統集成的全產業鏈協同發展格局。\n6月26日,埃夫特申請科創板上市。招股說明書公開內容顯示,2015年以來,埃夫特先後收購了噴塗機器人制造及系統集成商CMA、通過工業機器人系統集成商EVOLUT、中高端汽車白車身焊接系統集成商WFC,並戰略投資運動控制系統設計公司ROBOX,並在國內合資設立希美埃、埃華路、瑞博思等公司。截止目前,埃夫特及其下屬子公司共擁有境內外專利184件(包括髮明專利35件)及軟件著作權7件。\n推出可以像“寵物”一樣跟在用戶身後自己行走的智能行李箱,與環衛龍頭企業中聯環境共同發佈全球首臺全路況清掃、AI智能路徑規劃的無人駕駛掃地車及清掃機器人……據安徽酷哇機器人有限公司負責人何弢介紹,目前酷哇選擇依託於現有項目(如智能駕駛車輛或智能載物機器人項目)進行有計劃、針對性的專利產出,並針對競爭對手的產品或者專利進行圍欄式專利佈局,通過對競爭對手產品或者專利技術方案的研究,結合自身研發實力進行相應專利的預埋,用於專利攻防。\n企業通過參考專利技術方案的技術價值、市場價值、侵權可視度、使用該專利技術方案的產品的銷售區域、專利進國家的具體方式(PCT專利進國家或者通過巴黎公約要求優先權進國家)等因素,決定PCT專利申請的數量和進國家的專利技術方案。據統計,酷哇累計申請中國專利206件(包括髮明專利172件),其中智能載物機器人相關的技術方案166件,智能駕駛車輛相關的技術方案40件,佈局了10件PCT專利,同時佈局了2件美國專利申請。\n\n\n",
        "create_time": "2019-08-22 17:48:16"
    }
    result = es.create(index="netease_news_v1", doc_type="news", id='EN700FN104108DGB', body=body, ignore=[400, 409])
    print result


def create_index_type_datas():
    body = [
        {"index": {'_index': 'netease_news_v1', '_type': 'news', '_id': 'EN1001'}},
        {'id': 'EN1001', 'url': 'http://gz.news.163.com/19/0822/17/EN1.html', 'title': '智能標題1', 'content': '智能內容1', 'create_time': '2019-08-22 17:48:01'},
        {"index": {'_index': 'netease_news_v1', '_type': 'news', '_id': 'EN1002'}},
        {'id': 'EN1002', 'url': 'http://gz.news.163.com/19/0822/17/EN2.html', 'title': '智能標題2', 'content': '智能內容2', 'create_time': '2019-08-22 17:48:02'},
        {"index": {'_index': 'netease_news_v1', '_type': 'news', '_id': 'EN1003'}},
        {'id': 'EN1003', 'url': 'http://gz.news.163.com/19/0822/17/EN3.html', 'title': '智能標題3', 'content': '智能內容3', 'create_time': '2019-08-22 17:48:03'},
        {"index": {'_index': 'netease_news_v1', '_type': 'news', '_id': 'EN1004'}},
        {'id': 'EN1004', 'url': 'http://gz.news.163.com/19/0822/17/EN4.html', 'title': '智能標題4', 'content': '智能內容4', 'create_time': '2019-08-22 17:48:04'},
    ]
    result = es.bulk(index='netease_news_v1', doc_type='news', body=body)
    print result


def update_index_type_data():
    body = {
        "doc": {
            "title": "更新 智能機器人爲人類“分憂” 專利助推行業創新發展"
        }
    }
    result = es.update(index="netease_news_v1", doc_type="news", id="EN700FN104108DGB", body=body, ignore=[400, 409])
    print result
    get_index_type_data()


def delete_index_type_data():
    result = es.delete(index="netease_news_v1", doc_type="news", id="EN700FN104108DGB")
    print result


def get_index_type_data():
    result = es.get(index="netease_news_v1", doc_type="news", id='EN700FN104108DGB')
    news = result['_source']
    print news['url']
    print news['title']
    print news['content']
    print news['create_time']


def count_index_type_data():
    result = es.count(index='netease_news_v1', body={"query": {"match_all": {}}})
    print result


def search_index_type_data_1():
    # result = es.search(index='netease_news_v1', q='*')
    result = es.search(index='netease_news_v1', body={"query": {"match_all": {}}})
    hits = result['hits']['hits']
    for hit in hits:
        source = hit['_source']
        for key, value in source.items():
            print '%s %s' % (key, value)
        print '----------'


def search_index_type_data_2():
    # result = es.search(index='netease_news_v1', q='title:智能')
    result = es.search(index='netease_news_v1', body={"query": {"term": {"title": u"智能"}}})
    print result['_shards']['total']
    print result['hits']['total']
    hits = result['hits']['hits']
    for hit in hits:
        source = hit['_source']
        for key, value in source.items():
            print '%s %s' % (key, value)
        print '----------'


def search_index_type_data_3():
    result = es.search(index='netease_news_v1', q='title:智能 AND content:內容', scroll='2m', size=2)
    print result['_shards']['total']
    print result['hits']['total']
    for hit in result['hits']['hits']:
        source = hit['_source']
        for key, value in source.items():
            print '%s %s' % (key, value)
        print '----------'
    scroll_id = result['_scroll_id']
    next_result = es.scroll(scroll_id=scroll_id, scroll='2m')
    for hit in next_result['hits']['hits']:
        source = hit['_source']
        for key, value in source.items():
            print '%s %s' % (key, value)
        print '##########'

mapping文件netease_news.json

{
	"dynamic": "strict",
	"_source": {
		"excludes": ["id"]
	},
	"properties": {
		"id": {
			"type": "keyword"
		},
		"url": {
			"type": "keyword"
		},
		"title": {
			"analyzer": "ik_smart",
			"type": "text"
		},
		"content": {
			"analyzer": "ik_smart",
			"type": "text"
		},
		"create_time": {
			"type": "text"
		},
		"type": {
			"type": "keyword"
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章