python操作Elasticsearch (一、例子)


E lasticsearch是一款分布式搜索引擎,支持在大數據環境中進行實時數據分析。它基於Apache Lucene文本搜索引擎,內部功能通過ReST API暴露給外部。除了通過HTTP直接訪問Elasticsearch,還可以通過支持Java、JavaScript、Python及更多語言的客戶 端庫來訪問。它也支持集成Apache Hadoop環境。Elasticsearch在有些處理海量數據的公司中已經有所應用,如GitHub、Foursquare和SoundCloud等。

elasticsearch 他對外提供了rest的http的接口,貌似很強大的樣子。 但是咱們的一些數據平台市場會對於elasticsearch的數據進行分析,尤其是實時分析。 當然不能用 http的方式。

下面是http的方式的一個demo:

下面是查詢,/ceshi是索引,rui是type,搜索的內容是title為jones的數據

curl http://vim.xiaorui.cc:9200/ceshi/rui/_search?q=title:jones&size=5&pretty=true

 添加數據

curl -X POST -d '{"title":"jones","amount":5.7}'

 但是聽說,1.x之后不能直接curl,這不是重點忽略

下面介紹一個python使用elasticsearch的例子

from datetime import datetime
from elasticsearch import Elasticsearch

#連接elasticsearch,默認是9200
es = Elasticsearch()

#創建索引,索引的名字是my-index,如果已經存在了,就返回個400,
#這個索引可以現在創建,也可以在后面插入數據的時候再臨時創建
es.indices.create(index='my-index',ignore)
#{u'acknowledged':True}


#插入數據,(這里省略插入其他兩條數據,后面用)
es.index(index="my-index",doc_type="test-type",id=01,body={"any":"data01","timestamp":datetime.now()})
#{u'_type':u'test-type',u'created':True,u'_shards':{u'successful':1,u'failed':0,u'total':2},u'_version':1,u'_index':u'my-index',u'_id':u'1}
#也可以,在插入數據的時候再創建索引test-index
es.index(index="test-index",doc_type="test-type",id=42,body={"any":"data","timestamp":datetime.now()})


#查詢數據,兩種get and search
#get獲取
res = es.get(index="my-index", doc_type="test-type", id=01)
print(res)
#{u'_type': u'test-type', u'_source': {u'timestamp': u'2016-01-20T10:53:36.997000', u'any': u'data01'}, u'_index': u'my-index', u'_version': 1, u'found': True, u'_id': u'1'}
print(res['_source'])
#{u'timestamp': u'2016-01-20T10:53:36.997000', u'any': u'data01'}

#search獲取
res = es.search(index="test-index", body={"query":{"match_all":{}}}) 
print(res)
#{u'hits': 
#    {
#    u'hits': [
#        {u'_score': 1.0, u'_type': u'test-type', u'_id': u'2', u'_source': {u'timestamp': u'2016-01-20T10:53:58.562000', u'any': u'data02'}, u'_index': u'my-index'}, 
#        {u'_score': 1.0, u'_type': u'test-type', u'_id': u'1', u'_source': {u'timestamp': u'2016-01-20T10:53:36.997000', u'any': u'data01'}, u'_index': u'my-index'}, 
#        {u'_score': 1.0, u'_type': u'test-type', u'_id': u'3', u'_source': {u'timestamp': u'2016-01-20T11:09:19.403000', u'any': u'data033'}, u'_index': u'my-index'}
#    ], 
#    u'total': 5, 
#    u'max_score': 1.0
#    }, 
#u'_shards': {u'successful': 5, u'failed': 0, u'total':5}, 
#u'took': 1, 
#u'timed_out': False
#}
for hit in res['hits']['hits']:
    print(hit["_source"]) 
res = es.search(index="test-index", body={'query':{'match':{'any':'data'}}}) #獲取any=data的所有值
print(res)

 至於body里面參數的設置,具體請看:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM