赞
踩
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.6.3</version>
</dependency>
- @Configuration
- public class RestClientConfig extends AbstractElasticsearchConfiguration {
-
- @Override
- @Bean
- public RestHighLevelClient elasticsearchClient() {
- final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
- .connectedTo("xx.xxx.xxx.xx:9200") //地址
- .build();
- return RestClients.create(clientConfiguration).rest();
- }
- }
会返回两个客户端对象,分别是ElasticsearchOperations和RestHighLevelClient(更推荐使用)。前者是通过面向对象的形式来操作的,后者是通过客户端的方式操作的。
- /*
- 索引相关操作
- */
- public class Test1 {
-
- RestHighLevelClient restHighLevelClient;
-
- @Before
- public void init(){
- final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
- .connectedTo("xx.xxxx.xxx.xx:xxxx")
- .build();
- this.restHighLevelClient = RestClients.create(clientConfiguration).rest();
- }
-
- @Test//创建索引
- public void createIndex() throws IOException {
- CreateIndexRequest createIndexRequest = new CreateIndexRequest("products");
- //指定映射 参数1:指定映射json结构 参数2:指定数据类型
- createIndexRequest.mapping("{\n" +
- " \"properties\": {\n" +
- " \"id\":{\n" +
- " \"type\":\"integer\"\n" +
- " },\n" +
- " \"title\":{\n" +
- " \"type\":\"keyword\"\n" +
- " },\n" +
- " \"price\":{\n" +
- " \"type\":\"double\"\n" +
- " },\n" +
- " \"created_at\":{\n" +
- " \"type\":\"date\"\n" +
- " },\n" +
- " \"description\":{\n" +
- " \"type\":\"text\",\n" +
- " \"analyzer\": \"ik_max_word\"\n" +
- " }\n" +
- " }\n" +
- " }", XContentType.JSON);
- //参数1:创建索引请求对象 参数2:请求配置对象
- CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
- System.out.println("创建状态:"+createIndexResponse.isAcknowledged()); //打印返回信息
- restHighLevelClient.close(); //关闭资源
- }
-
- @Test//删除索引
- public void deleteIndex() throws IOException {
- AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(new DeleteIndexRequest("products"), RequestOptions.DEFAULT);
- System.out.println("删除状态:"+acknowledgedResponse.isAcknowledged()); //打印返回信息
- restHighLevelClient.close(); //关闭资源
- }
- }
- /*
- 文档相关操作(document)
- */
- public class Test2 {
- RestHighLevelClient restHighLevelClient;
-
- @Before
- public void init(){
- final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
- .connectedTo("xx.xxx.xxx.xx:9200")
- .build();
- this.restHighLevelClient = RestClients.create(clientConfiguration).rest();
- }
-
- @Test //创建文档
- public void createDoc() throws IOException {
- IndexRequest indexRequest = new IndexRequest("products");
- indexRequest.id("2") //手动指定文档的id,如果不指定则会用uuid
- .source("{\n" +
- " \"title\":\"瑞星咖啡\",\n" +
- " \"price\": 9.8,\n" +
- " \"created_at\":\"2023-11-18\",\n" +
- " \"description\":\"瑞星咖啡我最爱了,好喝\"\n" +
- "}", XContentType.JSON);
- //参数1:索引请求对象,参数2:请求配置对象
- IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
- System.out.println(indexResponse.status());
- restHighLevelClient.close();
- }
-
- @Test //修改文档
- public void updateDoc() throws IOException {
- UpdateRequest updateRequest = new UpdateRequest("products","1");
- updateRequest.doc("{\n" +
- " \"title\":\"库迪咖啡非\"\n" +
- " }",XContentType.JSON);
- //参数1:索引请求对象,参数2:请求配置对象
- UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
- System.out.println(updateResponse.status());
- restHighLevelClient.close();
- }
-
- @Test //删除文档
- public void deleteDoc() throws IOException {
- DeleteRequest deleteRequest = new DeleteRequest("products","2");
- //参数1:索引请求对象,参数2:请求配置对象
- DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
- System.out.println(deleteResponse.status());
- restHighLevelClient.close();
- }
-
- @Test //基于id查询文档
- public void searchDocById() throws IOException {
- GetRequest getRequest = new GetRequest("products", "1");
- GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
- System.out.println(getResponse.getId());
- System.out.println(getResponse.getSourceAsString());
- }
-
- }
- public class Test3 {
- RestHighLevelClient restHighLevelClient;
-
- @Before
- public void init(){
- final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
- .connectedTo("xx.xxx.xxx.xx:9200")
- .build();
- this.restHighLevelClient = RestClients.create(clientConfiguration).rest();
- }
-
- @Test //查询一个索引中的所有文档
- public void searchAll() throws IOException {
- SearchRequest searchRequest = new SearchRequest("products");
- searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));//查询所有
- //参数1:搜索请求对象 参数2:请求配置对象
- SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
- System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
- System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
- //拿到数据结果
- SearchHit[] hits = searchResponse.getHits().getHits();
- for(SearchHit hit:hits){
- String id = hit.getId();
- System.out.println("id: "+id+" source: "+hit.getSourceAsString());
- }
- }
-
-
- @Test //基于关键词查询
- public void search() throws IOException {
- SearchRequest searchRequest = new SearchRequest("products");
- searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("description","好喝")));//查询所有
- //参数1:搜索请求对象 参数2:请求配置对象
- SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
- System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
- System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
- //拿到数据结果
- SearchHit[] hits = searchResponse.getHits().getHits();
- for(SearchHit hit:hits){
- String id = hit.getId();
- System.out.println("id: "+id+" source: "+hit.getSourceAsString());
- }
- }
-
- /*
- * 分页查询
- * 排序
- * 字段
- */
- @Test //分页查询 与排序
- public void search2() throws IOException {
- SearchRequest searchRequest = new SearchRequest("products");
- SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
- searchSourceBuilder.query(QueryBuilders.matchAllQuery())
- .from(1) //起始位置 start=(page-1)*size
- .size(1) //每页显示条数
- .sort("price", SortOrder.ASC) //字段排序
- .fetchSource(new String[]{},new String[]{"created_at"}); //参数1:包含字段数组 参数2:排除字段数组
- searchRequest.source(searchSourceBuilder);//查询所有
- //参数1:搜索请求对象 参数2:请求配置对象
- SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
- System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
- System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
- //拿到数据结果
- SearchHit[] hits = searchResponse.getHits().getHits();
- for(SearchHit hit:hits){
- String id = hit.getId();
- System.out.println("id: "+id+" source: "+hit.getSourceAsString());
- }
- }
-
- @Test //高亮
- public void search3() throws IOException {
- SearchRequest searchRequest = new SearchRequest("products");
- SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
- HighlightBuilder highlightBuilder = new HighlightBuilder();
- highlightBuilder.requireFieldMatch(false).field("description").field("title").preTags("<span style='color:red;'>").postTags("</span>");
- searchSourceBuilder.query(QueryBuilders.termQuery("description","好喝"))
- .highlighter(highlightBuilder);
- searchRequest.source(searchSourceBuilder);//查询所有
- //参数1:搜索请求对象 参数2:请求配置对象
- SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
- System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
- System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
- //拿到数据结果
- SearchHit[] hits = searchResponse.getHits().getHits();
- for(SearchHit hit:hits){
- System.out.println("id: "+hit.getId()+" source: "+hit.getSourceAsString());
- //获取高亮字段
- Map<String, HighlightField> highlightFields = hit.getHighlightFields();
- if(highlightFields.containsKey("description")){
- System.out.println("description高亮结果: "+highlightFields.get("description").fragments()[0]);
- }
- if(highlightFields.containsKey("title")){
- System.out.println("title高亮结果: "+highlightFields.get("title").fragments()[0]);
- }
- }
- }
-
-
- @Test //过滤查询
- public void search4() throws IOException {
- SearchRequest searchRequest = new SearchRequest("products");
- SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
- searchSourceBuilder.query(QueryBuilders.matchAllQuery())
- .postFilter(QueryBuilders.idsQuery().addIds("1")); //指定过滤条件
- searchRequest.source(searchSourceBuilder);//查询所有
- //参数1:搜索请求对象 参数2:请求配置对象
- SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
- System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
- System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
- //拿到数据结果
- SearchHit[] hits = searchResponse.getHits().getHits();
- for(SearchHit hit:hits){
- String id = hit.getId();
- System.out.println("id: "+id+" source: "+hit.getSourceAsString());
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。