1. 不使用用户名密码连接
在Elasticsearch7.x版本中
Python使用下面的方式连接es:
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
print(es)
在es的8.x版本中
这种方式将不再适用,新的方式如下:
from elasticsearch import Elasticsearch
es = Elasticsearch('http://localhost:9200')
print(es)
2. 密码链接
python代码
from elasticsearch import Elasticsearch
es = Elasticsearch('http://localhost:9200', basic_auth=('username', 'password'))
print(es)
还有一种方式
es = Elasticsearch('http://username:password@localhost:9200')
print(es)
java代码
// 创建带有身份验证的RestClient
String username = "username"; // 替换为你的用户名
String password = "password"; // 替换为你的密码
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
// 添加基本身份验证
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
return httpClientBuilder;
}
});
client = new RestHighLevelClient(builder);
3. token 链接
python代码
headers = {'content-type': 'application/json', 'Authorization': 'your token'}
es_client = Elasticsearch(
"https://localhost",
headers=headers,
timeout=300,
retry_on_timeout=True
)
java代码
// 创建带有身份验证的RestClient
Header header = new BasicHeader("Authorization", "your token");
Header[] headers = {header};
RestClientBuilder builder = RestClient.builder(new HttpHost("https://localhost", 443, "https"))
.setDefaultHeaders(headers);
client = new RestHighLevelClient(builder);
4. fingerprint 链接
from elasticsearch import Elasticsearch
CERT_FINGERPRINT = "A5......"
# Password for the 'elastic' user generated by Elasticsearch
client = Elasticsearch(
"https://localhost:9200",
ssl_assert_fingerprint=CERT_FINGERPRINT,
basic_auth=(username, password)
)
这种方式需要Python3.10版本以上,而且如果使用aiohttp则无法访问。
5. ca证书
证书的位置在elasticsearch-8.2.0/config/certs/http_ca.crt路径下,因此只要将这个证书拿到就可以了。
from elasticsearch import Elasticsearch
es = Elasticsearch('https://localhost:9200',
basic_auth=(username, password),
ca_certs = './http_ca.crt',
verify_certs=True)
以上是总结的es连接方式