1、安装
pip install elastisearch
2、连接elasticsearch
from elasticsearch import Elasticsearch
es = Elasticsearch(hosts="192.168.28.25", port=9200, timeout=200)
3、创建索引
from elasticsearch import Elasticsearch
from datetime import datetime
class MyElasticsearch(object):
"""本次用的是elasticsearch==7.0.1的版本"""
def __init__(self):
"""初始化elastisearch 连接"""
# 测试环境
self.es = Elasticsearch(hosts='127.0.0.1', port=9200, timeout=200)
# 正式环境
# self.es = Elasticsearch(hosts='10.35.25.101', port=9200, timeout=200)
def create_index(self, index_name):
"""创建es索引"""
res = self.es.indices.create(index=index_name, body={
'settings': {
"number_of_shards": 2,
"number_of_replicas": 1
},
'mappings': {
'_source': {
'enabled': True
},
'properties': {
'server_ip': {'type': 'ip'},
'domain': {'type': 'keyword'},
'request_ip': {'type': 'ip'},
'request_location': {'type': 'keyword'},
'count_per_minute': {'type': 'integer'},
'start_time': {'type': 'date'},
'end_time': {'type': 'date'},
'uri_info': {'type': 'text'},
}
}
})
return res
def post_context(self, index_name, body_json):
"""往指定索引提交数据"""
res = self.es.index(index=index_name, body=body_json)
return res
if __name__ == '__main__':
json = {
"server_ip": "10.0.0.1",
"domain": "www.test.com",
"request_ip": "8.8.8.8",
"request_location": "福建福州",
"count_per_minute": 1000,
'start_time': "1596099159032",
'end_time': "1596099159032",
'uri_info': "/info",
}
es = MyElasticsearch()
print(es.post_context('test-index4', json))
# print(es.create_index('test-index4'))