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.common.xcontent.XContentType;
public class ElasticSearchExample {
private static final String HOST = "http://localhost:9200";
private static final RestClientBuilder builder = RestClient.builder(new HttpHost(HOST));
private static final RestHighLevelClient client = new RestHighLevelClient(builder);
public static void main(String[] args) throws IOException {
createIndex();
getData();
updateData();
deleteData();
client.close();
}
private static void createIndex() throws IOException {
IndexRequest request = new IndexRequest("posts", "doc", "1");
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2023-04-07\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println("Index Response Status:" + response.status());
}
private static void getData() throws IOException {
GetRequest getRequest = new GetRequest("posts", "doc", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());
}
private static void updateData() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("posts", "doc", "1");
String jsonString = "{" +
"\"message\":\"updated message\"" +
"}";
updateRequest.doc(jsonString, XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOp
评论已关闭