当前位置:   article > 正文

SpringBoot整合ES

springboot整合es

1. 创建springboot项目引入ES依赖
es与spring以及分词器要有严格的版本对应
2. 配置文件

spring:
  elasticsearch:
    rest:
      uris: ip:9200
  • 1
  • 2
  • 3
  • 4

3. 配置客户端

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {

    @Value("${spring.elasticsearch.rest.uris}")
    private String uris;


    @Override
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(uris)
                .withConnectTimeout(1000)
                .withSocketTimeout(30000)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

4. 创建索引
定义常量字符串保存创建索引库

public class ShopConstants {
    public static final String MAPPING_TEMPLATE = "{\n" +
            "\"properties\":{\n" +
            "\"id\":{\n" +
            "\"type\":\"keyword\"\n" +
            "},\n" +
            "\"shopName\":{\n" +
            "\"type\":\"text\",\n" +
            "\"copy_to\":\"all\"\n" +
            "},\n" +
            "\"shopContent\":{\n" +
            "\"type\":\"text\",\n" +
            "\"index\":false\n" +
            "},\n" +
            "\"score\":{\n" +
            "\"type\":\"integer\"\n" +
            "},\n" +
            "\"userName\":{\n" +
            "\"type\":\"keyword\",\n" +
            "\"copy_to\":\"all\"\n" +
            "},\n" +
            "\"all\":{\n" +
            "\"type\":\"text\"\n" +
            "}\n" +
            "}\n" +
            "}";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

restClient方式创建索引库

	@Test
    public void createIndex() {
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest("shop");
            createIndexRequest.mapping(MAPPING_TEMPLATE, XContentType.JSON);
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            log.info("创建索引状态:{}", createIndexResponse.isAcknowledged());
        } catch (Exception e) {
            log.info("创建失败:{}", e.getMessage());
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这里需要注意的是,引入的CreateIndexRequestimport org.elasticsearch.client.indices.CreateIndexRequest;
如果引入import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;d 的话需要这么写

createIndexRequest.mapping("_doc",MAPPING_TEMPLATE, XContentType.JSON);
  • 1

5. 判断索引库是否存在

	@Test
    public void existsIndex() {
        try {
            GetIndexRequest indexRequest = new GetIndexRequest("shop");
            boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
            log.info("索引是否存在:{}", exists);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

6. 删除索引库

	@Test
    public void delIndex() {
        try {
            AcknowledgedResponse shopIndex = restHighLevelClient.indices().delete(new DeleteIndexRequest("shop"), RequestOptions.DEFAULT);
            log.info("删除索引:{}", shopIndex.isAcknowledged());
        } catch (Exception e) {
            log.info("删除失败:{}", e.getMessage());
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

7. 新增单条文档

    @Test
    public void createDoc() {
        IndexRequest indexRequest = new IndexRequest("shop");
        Shop shop = new Shop("1", "小米手机店铺", "小米手机买卖", 1, "张三");
        indexRequest.id(shop.getId());
        indexRequest.source(JSONUtil.toJsonStr(shop), XContentType.JSON);
        try {
            IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            log.info("创建结果:{}", index.getResult());
        } catch (Exception e) {
            log.info("创建失败:{}", e.getMessage());
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

8. 单条查询文档

    @Test
    public void selectOneDoc() {
        try {
            GetRequest getRequest = new GetRequest("shop", "1");
            GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            log.info("查询结果:{}", documentFields.getSourceAsString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

9. 修改文档

    @Test
    public void updateDoc() {
        UpdateRequest updateRequest = new UpdateRequest("shop","1");
        Shop shop = new Shop();
        shop.setShopName("小米手机店铺123");
        updateRequest.doc(JSONUtil.toJsonStr(shop), XContentType.JSON);
        try {
            UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            log.info("更新结果:{}", update.getResult());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

10. 删除文档

    @Test
    public void delDoc() {
        DeleteRequest deleteRequest = new DeleteRequest("shop","1");
        try {
            DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            log.info("删除结果:{}", delete.getResult());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

11. 批量导入文档

    @Test
    public void batchCreateDoc() {
        try {
            Shop shop = new Shop("1", "小米手机店铺", "小米手机买卖", 1, "张三");
            Shop shop2 = new Shop("2", "华为手机店铺", "华为手机买卖", 2, "李四");
            Shop shop3 = new Shop("3", "苹果手机店铺", "苹果手机买卖", 3, "可子");
            List<Shop> shopList = Arrays.asList(shop, shop2, shop3);
            BulkRequest bulkRequest = new BulkRequest();
            for (Shop shop1 : shopList) {
                bulkRequest.add(new IndexRequest("shop")
                        .id(shop1.getId())
                        .source(JSONUtil.toJsonStr(shop1), XContentType.JSON));
            }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            //返回false表示没有失败的情况
            log.info("批量创建结果:{}", bulk.hasFailures());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

12. 复杂查询

a 查询所有
在这里插入图片描述

    @Test
    public void selectDoc() {
        SearchRequest searchRequest = new SearchRequest("shop");
        searchRequest.source().query(QueryBuilders.matchAllQuery());
        try {
            SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = documentFields.getHits().getHits();
            for (SearchHit hit : hits) {
                log.info("查询结果:{}", hit.getSourceAsString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

b 多字段查询
在这里插入图片描述

    @Test
    public void selectDoc() {
        SearchRequest searchRequest = new SearchRequest("shop");
        searchRequest.source().query(QueryBuilders.multiMatchQuery("可子", "shopName", "userName"));
        try {
            SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = documentFields.getHits().getHits();
            for (SearchHit hit : hits) {
                log.info("查询结果:{}", hit.getSourceAsString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

c 精准查询

这里需要注意的是,设置为keyword类型的字段才能使用精准查询
在这里插入图片描述

    @Test
    public void selectDoc() {
        SearchRequest searchRequest = new SearchRequest("shop");
        searchRequest.source().query(QueryBuilders.termQuery("userName", "可子"));
        try {
            SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = documentFields.getHits().getHits();
            for (SearchHit hit : hits) {
                log.info("查询结果:{}", hit.getSourceAsString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

d 范围查询
在这里插入图片描述

    @Test
    public void selectDoc() {
        SearchRequest searchRequest = new SearchRequest("shop");
        searchRequest.source().query(QueryBuilders.rangeQuery("score").gt(2));
        try {
            SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = documentFields.getHits().getHits();
            for (SearchHit hit : hits) {
                log.info("查询结果:{}", hit.getSourceAsString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/469345
推荐阅读
相关标签
  

闽ICP备14008679号