python連接ES進行數據過濾刪除,新增查詢、創建索引功能


# -*- coding: utf-8 -*-
"""
@Time :2020/06/04
@UpTime :2020/06/23
@Author :Mr.Yang
@File :ElasticSearch_operations.py
@Software :PyCharm
@Description :對ES進行查詢,創建索引、按時間戳刪除操作(增加寫入操作待定)
@plug-in package:目前我所使用的是7.7.1的插件包,pip install elasticsearch==7.7.1
"""

import time
import datetime
import json
import sys
from elasticsearch import Elasticsearch

"""當前時間及時間戳轉換"""
Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
"""當前時間計算"""
now_time = datetime.date.today()
"""當前時間的前一個月"""
last_time = datetime.datetime.now() - datetime.timedelta(days = 1)
"""字符格式類型轉換"""
now_time = last_time.strftime("%Y-%m-%d %H:%M:%S")
"""換算時間戳為毫秒級"""
mtime = (int(time.mktime(last_time.timetuple())) * 1000)

"""ES連接配置"""
es_host = ['', '', '']
es = Elasticsearch(hosts=es_host)

"""ES查詢、刪除修改下列參數"""
index_name = ""
id = ""

def query(index_name,id):
"""查詢轉換為json格式"""
res = es.get(index=index_name,id=id)
print json.dumps(res, sort_keys=True, indent=4, separators=(', ', ': '))#['hits']['hits']

def deles():
"""查詢所有數據"""
noll = {
"query": {
"bool": {
"must_not": {
"exists": {
"field": "updateTime"
}
}
}
}
}
"""小於更新時間戳"""
updatetime = {
"query":{
"range":{
"updateTime": {
"lte": mtime
}
}
}
}
"""小於創建時間戳"""
createtime = {
"query":{
"range":{
"createTime":{
"lte":mtime
}
}
}
}

#updata = es.search(index=index_name,body=updatetime)
#create = es.search(index=index_name,body=createtime)
"""查詢updateTime是否為空"""
updatanoll = es.search(index=index_name,body=noll)
"""刪除更新時間小於設定時間戳的數據"""
es.delete_by_query(index=index_name, body=updatetime)
"""查詢結果轉換為json格式"""
#res = json.dumps(updata, sort_keys=True, indent=4, separators=(', ', ': ')
"""查詢結果匹配到單個值"""
#res = json.dumps(updatenot["hits"]["hits"][0]["_source"]["updateTime"], sort_keys=True, indent=4, separators=(', ', ': '))
"""刪除更新時間為空的數據,以插入時間做判斷"""
if updatanoll != " ":
es.delete_by_query(index=index_name,body=createtime)
else:
print "無更新時間為空的數據"

def create():
"""創建索引"""
body = {
"settings":{
"index":{
"number_of_shards": "3",
"number_of_replicas": "2"
}
}
}
try:
result = es.indices.create(index='ceshi',body=body)
print result
except Exception as err:
print err


choose = input("請輸出選項1/2/3(1查詢,2過濾以更新時間為1個月以前的刪除,3創建索引):")
if choose == 1:
query(index_name, id)
elif choose == 2:
deles()
elif choose == 3:
create()
else:
print "請正確輸入參數(1/2/3(1查詢,2過濾以更新時間為1個月以前的刪除,3創建索引)"


免責聲明!

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



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