1. 程式人生 > >ES(Elasticsearch)scroll查詢獲取所有資料的某個欄位

ES(Elasticsearch)scroll查詢獲取所有資料的某個欄位

在ElasticSearch中實現分頁查詢的方式有兩種,分別為深度分頁(from-size)和快照分頁(scroll)

  1. 快照分頁(scroll)
           相對於from和size的分頁來說,使用scroll可以模擬一個傳統資料的遊標,記錄當前讀取的文件資訊位置。這個分頁的用法,不是為了實時查詢資料,而是為了一次性查詢大量的資料(甚至是全部的資料)。因為這個scroll相當於維護了一份當前索引段的快照資訊,這個快照資訊是你執行這個scroll查詢時的快照。在這個查詢後的任何新索引進來的資料,都不會在這個快照中查詢到。但是它相對於from和size,不是查詢所有資料然後剔除不要的部分,而是記錄一個讀取的位置,保證下一次快速繼續讀取。

       curl -XGET 'localhost:9200/twitter/tweet/_search?scroll=1m' -d '
       {
            "query": {
                 "match" : {
                 "title" : "elasticsearch"
              }
           }
        }
    

    該查詢會自動返回一個_scroll_id,通過這個id(經過base64編碼)可以繼續查詢

    curl -XGET  '叢集節點IP:9200/_search/scroll?scroll=1m&scroll_id=c2Nhbjs2OzM0NDg1ODpzRlBLc0FXNlNyNm5JWUc1'
    
  2. python 實現

    #coding: utf-8
    from elasticsearch import Elasticsearch
    if __name__ == "__main__":
    	hosts = 'localhost:9200/' 
    	es = Elasticsearch(hosts=hosts, maxsize=25)
    	index_name = 'test_es'
    	dbname='test_bj'
    	tbl='test_table1'
    	test_table = "%s.%s" % (dbname, tbl)
    	query_json = {"match_all": {}}
    	es_data=es.search(index=index_name, doc_type=dbname, body={"query": query_json},filter_path=["_scroll_id","hits.total","hits.hits._id"], scroll = '5m',size =1000,timeout='1s')
    	es_ids = [ int(id['_id'])  for id in es_data.get("hits").get("hits")]
    	scroll_id = es_data['_scroll_id']
    	es_total = es_data.get('hits').get('total')
    	for i in range(es_total/1000):
    		res = es.scroll(scroll_id=scroll_id,scroll='5m')
    		es_ids += [int(id['_id']) for id in res.get('hits').get('hits')]
    	sql_not_exist = "SELECT id from " + test_table +" where id not in " + str(tuple(es_ids))
    	cur_sell.execute(sql_not_exist)
    	print "es缺少資料"+str(cur_sell.fetchall())
    

參考:
https://blog.csdn.net/u013514928/article/details/78749419
http://www.cnblogs.com/blue163/p/8126156.html