导入依赖 导入pom文件 依据自己版本dependency groupIdorg.elasticsearch.client/groupId artifactIdelasticsearch-rest-high-level-client/artifactId version7.4.2/version/dependency设置版本properties java.version1.8/java.version e
导入依赖
导入pom文件 依据自己版本 <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.4.2</version> </dependency> 设置版本 <properties> <java.version>1.8</java.version> <elasticsearch.version>7.4.2</elasticsearch.version> </properties> //新建配置类 并设置Client和指定端口号 @Configuration public class GulimallElasticSearchConfig { @Bean //放到容器中 public RestHighLevelClient esRestClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("192.168.56.10", 9200, "http"))); return client; } }操作文档 https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html
GulimallElasticSearchConfig
@Configuration public class GulimallElasticSearchConfig { 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 //放到容器中 public RestHighLevelClient esRestClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("192.168.56.10", 9200, "http"))); return client; } }测试简单索引
@Autowired private RestHighLevelClient client;
@Test //测试es 存储数据 public void indexData() throws IOException { IndexRequest indexRequest = new IndexRequest("users"); indexRequest.id("1"); User user = new User(); user.setUserName("咱三"); user.setAge(18); user.setGender("男"); String jsonString = JSON.toJSONString(user);//转换String类型 indexRequest.source(jsonString, XContentType.JSON);//保存内容 //执行操作 IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS); // System.out.println(index); }