1.导入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
2.配置bean及设置一些安全头信息
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// builder.addHeader("Authorization", "Bearer " + TOKEN);
// builder.setHttpAsyncResponseConsumerFactory(
// new HttpAsyncResponseConsumerFactory
// .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
COMMON_OPTIONS = builder.build();
}
@Bean
RestHighLevelClient client() {
RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.56.100", 9200, "http"));
return new RestHighLevelClient(builder);
}
3.使用Elasticsearch-Rest-Client进行测试
@Autowired
RestHighLevelClient client;
@Test
void contextLoads() throws IOException {
Product product = new Product();
product.setName("hdl");
product.setId(10);
IndexRequest request = new IndexRequest("product").id("20")
.source(JSON.toJSONString(product),XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
}