ES客户端接入方式
Elasticsearch(ES)客户端是用于与ES集群交互的库。客户端使用特定语言与ES集群通信。以下是几种常见的ES客户端接入方式:
- 使用Elasticsearch-Java-API
Elasticsearch-Java-API是Elasticsearch官方提供的Java客户端。以下是一个简单的例子,展示如何使用它来创建一个索引:
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
public class ElasticsearchExample {
public static void main(String[] args) {
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
try {
IndexRequest request = new IndexRequest("posts", "_doc", "1");
request.source(XContentType.JSON, "title", "Some short title", "content", "Some content");
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
- 使用Elasticsearch-Python-API
Elasticsearch-Python-API是Elasticsearch官方提供的Python客户端。以下是一个简单的例子,展示如何使用它来创建一个索引:
from elasticsearch import Elasticsearch
es = Elasticsearch(["http://localhost:9200"])
response = es.index(index="posts", id=1, document={'title': 'Some short title', 'content': 'Some content'})
print(response)
- 使用Spring Data Elasticsearch
Spring Data Elasticsearch是Spring Data项目的一部分,用于简化与Elasticsearch的集成。以下是一个简单的例子,展示如何使用Spring Data Elasticsearch来创建一个索引:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
public class ElasticsearchExample {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public void createIndex(String
评论已关闭