https://www.bilibili.com/video/BV1py4y1r7Ar?from=search&seid=14817215112859046317
笔记 https://blog.csdn.net/qq_20051535/category_10772271.html
一、配置
1、引入依赖
2、建立Config
建立一个类,我们命名为 ElasticSearchConfig 把它放在了Config文件夹作为我们的配置文件
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author ruipeng.qi
**/
@Configuration
public class ElasticSearchConfig {
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
COMMON_OPTIONS = builder.build();
}
@Bean
public RestHighLevelClient client() {
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200)));
}
}
二、Test测试新增
我们尝试新增一个User对象。我们采用内部类形式定义对象,之后新建一个实例,让他的名字叫 zhangsan;性别是 男;年龄18
注意,下面代码中 @Data 注解作用是自动添加 GET 和 SET 方法,和项目本身没有太大关系
运行后尝试查询是否添加成功。
import com.alibaba.fastjson.JSON;
import com.qiruipeng.es.config.ElasticSearchConfig;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest
class EsApplicationTests {
@Autowired
private RestHighLevelClient client;
/**
* 测试存储数据到es
* 更新也可以
*/
@Test
void indexData() throws IOException {
IndexRequest indexRequest = new IndexRequest("users");
indexRequest.id("1");
User user = new User("zhangsan", "男", 18);
String jsonString = JSON.toJSONString(user);
indexRequest.source(jsonString, XContentType.JSON);
//执行操作
IndexResponse index = client.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
//提取有用的操作数据
System.out.println(index);
}
@Data
static class User{
private String userName;
private String gender;
private Integer age;
public User(String userName, String gender, Integer age) {
this.userName = userName;
this.gender = gender;
this.age = age;
}
}