创建配置文件8 8 2.5.4 org.springframework.boot spring-boot-dependencies${spring-boot.version} pom import org.springframework.boot spring-boot-starterorg.springframework.boot spring-boot-starter-testtest org.junit.vintage junit-vintage-engine//elasticsearch-rest-high-level-client中elasticsearch-rest-client版本不对应,需要额外导入,否则会出现有些方法使用报错 org.elasticsearch.client elasticsearch-rest-high-level-client7.15.2 org.elasticsearch.client elasticsearch-rest-client7.15.2 org.elasticsearch elasticsearch7.15.2
spring: application: name: service-search db: elasticsearch: # 根据自己的ip和端口设置,一般端口为9200,有多个用英文逗号隔开 hostnameList: localhost:9200创建配置类
@Configuration public class ElasticsearchConfig { @Value("${db.elasticsearch.hostnameList}") private String hostnameList; // 销毁时关闭 close为自带的 @Bean(destroyMethod = "close") public RestHighLevelClient restHighLevelClient() { String[] strings = hostnameList.split(","); HttpHost[] httpHost = new HttpHost[strings.length]; for (int i = 0; i < strings.length; i++) { String item = strings[i]; httpHost[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http"); } return new RestHighLevelClient(RestClient.builder(httpHost)); } }创建启动类
@SpringBootApplication public class SearchApplication { public static void main(String[] args) { SpringApplication.run(SearchApplication.class, args); } }编写测试类
查询数据
@SpringBootTest public class EsDemo { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void getData() throws IOException { GetRequest getRequest = new GetRequest("book", "1"); // 条件查询的参数 String[] includes = new String[]{"name", "description"}; String[] excludes = Strings.EMPTY_ARRAY; // 创建条件查询 FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes); // 添加条件查询参数 getRequest.fetchSourceContext(fetchSourceContext); // 执行 // 同步 GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); System.out.println(response.getId()); System.out.println(response.getVersion()); System.out.println(response.getSourceAsString()); // 异步,不会阻塞线程 ActionListenerlistener = new ActionListener () { @Override public void onResponse(GetResponse getResponse) { System.out.println(getResponse.getId()); System.out.println(getResponse.getVersion()); System.out.println(getResponse.getSourceAsString()); } @Override public void onFailure(Exception e) { e.printStackTrace(); } }; restHighLevelClient.getAsync(getRequest, RequestOptions.DEFAULT, listener); // 配置类中定义了close方法,因此启动延迟,方便观察数据 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }
添加数据
@Test public void addData() throws IOException { // 构建请求 IndexRequest indexRequest = new IndexRequest("book", "_doc", "5"); // 方法1 // String jsonString = "{n" + // " "name": "java",n" + // " "description": "后端",n" + // " "timestamp": "2021-11-24 18:08:00",n" + // " "price": 31n" + // "}"; // indexRequest.source(jsonString, XContentType.JSON); // 方法2 // HashMaphashMap = new HashMap<>(); // hashMap.put("name", "php"); // hashMap.put("description", "后端"); // hashMap.put("timestamp", "2021-11-24 18:08:00"); // hashMap.put("price", "31"); // indexRequest.source(hashMap); // 方法3 // XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); // jsonBuilder.startObject(); // { // jsonBuilder.field("name", "node.js"); // jsonBuilder.field("description", "后端"); // jsonBuilder.field("price", "31"); // jsonBuilder.timeField("timestamp", "2021-11-24 18:08:00"); // } // jsonBuilder.endObject(); // indexRequest.source(jsonBuilder); // 方法4 indexRequest.source("name", "c#", "description", "后端", "price", "31", "timestamp", "2021-11-24 18:08:00"); // 可选参数 .... // indexRequest.timeout(Timevalue.timevalueMillis(1)); // 同步 IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); System.out.println(response.getId()); // 异步 ActionListener listener = new ActionListener () { @Override public void onResponse(IndexResponse response) { System.out.println(response.getId()); } @Override public void onFailure(Exception e) { e.printStackTrace(); } }; restHighLevelClient.indexAsync(indexRequest, RequestOptions.DEFAULT, listener); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
更新数据
@Test public void upData() throws IOException { UpdateRequest request = new UpdateRequest("book", "4"); HashMaphashMap = new HashMap<>(); hashMap.put("name", "C++"); request.doc(hashMap); // 同步 UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT); System.out.println(response.getId()); // 异步 ActionListener listener = new ActionListener () { @Override public void onResponse(UpdateResponse response) { System.out.println(response.getId()); } @Override public void onFailure(Exception e) { e.printStackTrace(); } }; restHighLevelClient.updateAsync(request, RequestOptions.DEFAULT, listener); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
删除数据
@Test public void deleteData() throws IOException { DeleteRequest request = new DeleteRequest("book", "5"); // 同步 DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT); System.out.println(response.getResult()); // 异步 ActionListenerlistener = new ActionListener () { @Override public void onResponse(DeleteResponse response) { System.out.println(response.getResult()); } @Override public void onFailure(Exception e) { e.printStackTrace(); } }; restHighLevelClient.deleteAsync(request,RequestOptions.DEFAULT,listener); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
批量 *** 作
@Test public void bulkData() throws IOException { BulkRequest request = new BulkRequest(); request.add(new IndexRequest("book").id("7").source(XContentType.JSON, "name", "c#", "description", "后端", "price", "31", "timestamp", "2021-11-24 18:08:00")); request.add(new UpdateRequest("book", "4").doc("name", "node")); // 同步 BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); for (BulkItemResponse bulkItemResponse : response) { DocWriteResponse responseResponse = bulkItemResponse.getResponse(); switch (bulkItemResponse.getOpType()) { case INDEX: System.out.println("CREATE or INDEX:" + responseResponse.getResult()); break; case CREATE: System.out.println("CREATE:" + responseResponse.getResult()); break; case UPDATE: System.out.println("UPDATE:" + responseResponse.getResult()); break; case DELETE: System.out.println("DELETE:" + responseResponse.getResult()); break; } } // 异步 ActionListenerlistener = new ActionListener () { @Override public void onResponse(BulkResponse response) { for (BulkItemResponse bulkItemResponse : response) { DocWriteResponse responseResponse = bulkItemResponse.getResponse(); switch (bulkItemResponse.getOpType()) { case INDEX: // 代表创建或者全替换,个人根据测试推断 System.out.println("INDEX:" + responseResponse.getResult()); break; case CREATE: System.out.println("CREATE:" + responseResponse.getResult()); break; case UPDATE: System.out.println("UPDATE:" + responseResponse.getResult()); break; case DELETE: System.out.println("DELETE:" + responseResponse.getResult()); break; } } } @Override public void onFailure(Exception e) { e.printStackTrace(); } }; restHighLevelClient.bulkAsync(request, RequestOptions.DEFAULT, listener); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
本人接触后端时间不长,欢迎各位大神指教
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)