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.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;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.common.xcontent.XContentType;
public class ElasticSearchJavaClientExample {
public static void main(String[] args) throws IOException {
// 创建Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
// 索引一个文档
IndexRequest indexRequest = new IndexRequest("posts");
indexRequest.id("1");
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2023-04-07\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
indexRequest.source(jsonString, XContentType.JSON);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
// 获取一个文档
GetRequest getRequest = new GetRequest("posts", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
// 删除一个文档
DeleteRequest deleteRequest = new DeleteRequest("posts", "1");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
// 搜索文档
SearchRequest searchRequest = new SearchRequest("posts");
SearchSourceBuilder searchSourceBuilder = ne
评论已关闭