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.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
public class ElasticSearchExample {
private RestHighLevelClient client;
public ElasticSearchExample(String hostname, int port) {
this.client = new RestHighLevelClient(
RestClient.builder(new HttpHost(hostname, port, "http")));
}
public void indexDocument() throws IOException {
IndexRequest request = new IndexRequest("index_name", "doc", "1");
request.source("field", "value");
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
}
public void getDocument() throws IOException {
GetRequest request = new GetRequest("index_name", "doc", "1");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
}
public void updateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("index_name", "doc", "1");
request.doc("field", "new_value");
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
}
public void deleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("index_name", "doc", "1");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
}
public void closeClient() throws IOException {
client.close();
}
public static void main(String[] args) {
ElasticSearchExample example = new ElasticSearchExample("localhost", 9200);
try {
// 创建文档
example.indexDocument();
// 获取文档
example.getDocument();
// 更新文档
example.updateDocument();
评论已关闭