一 什么是 ElasticSearch
Elasticsearch 是一個分布式可擴展的實時搜索和分析引擎,一個建立在全文搜索引擎 Apache Lucene(TM) 基礎上的搜索引擎.當然 Elasticsearch 並不僅僅是 Lucene 那么簡單,它不僅包括了全文搜索功能,還可以進行以下工作:
- 分布式實時文件存儲,並將每一個字段都編入索引,使其可以被搜索。
- 可實現億級數據實時查詢
- 實時分析的分布式搜索引擎。
- 可以擴展到上百台服務器,處理PB級別的結構化或非結構化數據。
二 安裝(windows下)
注意:Elasticsearch是用Java開發的,最新版本的Elasticsearch需要安裝jdk1.8以上的環境
安裝包下載完,解壓,進入到bin目錄,啟動 elasticsearch.bat 即可
三 python操作ElasticSearch
from elasticsearch import Elasticsearch # 創建ES對象 obj=Elasticsearch() # 創建索引index:索引的名字,body:數據,ignore:狀態碼 result=obj.indices.create(index="user",body={"userid":"1","username":"maple"},ignore=400) print(result) # {'error': {'root_cause': [{'type': 'parse_exception', 'reason': 'unknown key [userid] for create index'}], 'type': 'parse_exception', 'reason': 'unknown key [userid] for create index'}, 'status': 400} # 刪除索引 result = obj.indices.delete(index='user', ignore=[400, 404]) result = obj.delete(index='news', doc_type='politics', id=1) # 插入數據 data={"userid":"1","username":"maple","password":"123"} # index:索引名字,id:文檔ID,doc_type:文檔類型,body:數據 result=obj.create(index="news",doc_type="politics", id=1, body=data) # {'_index': 'news', '_type': 'politics', '_id': '1', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1} print(result) # 更新數據 ''' 不用doc包裹會報錯 ActionRequestValidationException[Validation Failed: 1: script or doc is missing ''' data ={"doc":{"userid": "1", "username": "maple","password":"123456","test":"測試"}} result = obj.update(index="news", doc_type="politics", body=data, id=1) # {'_index': 'news', '_type': 'politics', '_id': '1', '_version': 7, 'result': 'updated', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 6, '_primary_term': 1} print(result) # 查詢所有文檔 query={"query":{"match_all":{}}} # 查找名字叫maple的所有文檔 # query = {'query': {'term': {'username': 'maple'}}} # 查找年齡大於11的所有文檔 # query = {'query': {'range': {'age': {'gt': 11}}}} all_doc=obj.search(index="news", body=query) # {'userid': '1', 'username': 'maple', 'password': '123456', 'test': '測試'} print(all_doc["hits"]["hits"][0]["_source"])