package com.yqq.app13;


import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
* @Author yqq
* @Date 2021/11/30 15:30
* @Version 1.0
*/
public class IndexTest {
RestHighLevelClient client;
@Before
public void init(){
// 创建客户端对象,链接ES
client = new RestHighLevelClient(
RestClient.builder(new HttpHost("node0",9200,"http")));
}
@Test
public void createIndex() throws IOException {
// 创建请求对象
CreateIndexRequest request = new CreateIndexRequest("student");
request.settings(Settings.builder()
.put("index.number_of_shards",1)
.put("index.number_of_replicas",1)
);
// 发送请求
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
}
@Test
public void mappingIndex(){
// 创建请求对象
PutMappingRequest request = new PutMappingRequest("student");
request.source("{\"properties\": {" +
" \"id\": {" +
" \"type\": \"integer\"," +
" \"store\": true," +
" \"index\": true" +
" }," +
" \"name\": {" +
" \"type\": \"text\"," +
" \"store\": true," +
" \"index\": true" +
" }," +
" \"info\": {" +
" \"type\": \"text\"," +
" \"store\": true," +
" \"index\": true" +
" }" +
" }}", XContentType.JSON);
//发送请求
try {
client.indices().putMapping(request,RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void deleteIndex(){
// 创建请求对象
DeleteIndexRequest request = new DeleteIndexRequest("student");
try {
//发送请求
client.indices().delete(request,RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void close(){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}