先直接上代码,最简单的连接使用
安装依赖包:pip install elasticsearch,先体验下最简单的创建index,修改,查询功能
下面的初始化连接信息需要替换ip,密码pwd
一:python代码
from datetime import datetime
from elasticsearch import Elasticsearch
client = Elasticsearch('http://ip:9200',http_auth=("elastic", pwd))
# 创建
def index():
doc = {
'author': 'author_name',
'text': 'Interesting content...',
'timestamp': datetime.now(),
}
resp = client.index(index="test-index", id=1, document=doc)
print(resp['result'])
def query():
query = {
"query":{
"match":{
"text":"loleina"
}
}
}
result = client.search(index="test-index",body=query)
print(result)
for hit in result['hits']['hits']:
print(hit['_source'])
def update_doc():
update_doc ={
"doc":{
'text': 'loleina now do it',
}
}
client.update(index="test-index", id=1, body = update_doc )
if __name__ == '__main__':
index()
update_doc()
query()
二:连接报错
基于上一篇文章,如果现在就直接使用基础认证连接服务器,会报错:
elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: ProtocolError(('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))))
而服务器也会报错
三:原因分析
因为服务端开启后,就会自动注入一些安装配置信息到配置文件
# Enable security features
xpack.security.enabled: true
xpack.security.enrollment.enabled: true
# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
xpack.security.http.ssl:
enabled: true
keystore.path: certs/http.p12
# Enable encryption and mutual authentication between cluster nodes
xpack.security.transport.ssl:
enabled: true
verification_mode: certificate
keystore.path: certs/transport.p12
truststore.path: certs/transport.p12
# Create a new cluster with the current node only
四:解决办法
安全认证默认是打开的,http协议也开启了ssl,这里如果想只用用户名和密码去连服务,有1种解决办法适合我们初学者,直接修改这个配置文件里的。(也可以去配置ssl证书,官网文档有介绍,初始化的时候多一些参数)
xpack.security.http.ssl:
enabled: false
然后重启服务,重新运行程序,连接成功
后台日志正常写入: