美文网首页
ES 整合SpringBoot配置和使用

ES 整合SpringBoot配置和使用

作者: 小P聊技术 | 来源:发表于2021-03-18 08:24 被阅读0次

    1 介绍

    因为springboot整合es的问题,这里不使用 elasticsearch7.4.1版本,使用 elasticsearch6.4.3 版本。

    具体的配置可参考博文 《ES elasticsearch的安装和配置》https://blog.csdn.net/qq_15769939/article/details/114249211

    elasticsearch6.4.3下载https://download.csdn.net/download/qq_15769939/15655187

    elasticsearch6.4.3中文分词器下载https://download.csdn.net/download/qq_15769939/15655142

    2 配置信息

    2.1 pom文件

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
                <!--<version>2.1.5.RELEASE</version>-->
                <version>2.2.2.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    

    2.2 yml文件

    spring:
      # ES配置
      data:
        elasticsearch:
          cluster-name: es6
          cluster-nodes: 192.168.51.5:9300
    

    2.3 解决Netty报错问题

    import org.springframework.context.annotation.Configuration;
    import javax.annotation.PostConstruct;
    
    @Configuration
    public class ESConfig {
    
        /**
         * 解决netty引起的issue
         */
        @PostConstruct
        void init() {
            System.setProperty("es.set.netty.runtime.available.processors", "false");
        }
    
    }
    

    3 API调用

    import com.auskat.ESApplication;
    import com.auskat.es.pojo.Stu;
    import org.elasticsearch.action.index.IndexRequest;
    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.elasticsearch.search.SearchHit;
    import org.elasticsearch.search.SearchHits;
    import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
    import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
    import org.elasticsearch.search.sort.FieldSortBuilder;
    import org.elasticsearch.search.sort.SortBuilder;
    import org.elasticsearch.search.sort.SortOrder;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
    import org.springframework.data.elasticsearch.core.SearchResultMapper;
    import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
    import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
    import org.springframework.data.elasticsearch.core.query.*;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = {ESApplication.class})
    public class ESTest {
        @Autowired
        private ElasticsearchTemplate esTemplate;
    }
    

    3.1 索引操作

     /**
         * 不建议使用 ElasticsearchTemplate 对索引进行管理(创建索引,更新映射,删除索引)
         * 索引就像是数据库或者数据库中的表,我们平时是不会通过java代码频繁的去创建修改删除数据库的或者修改数据库的
         * 我们只会针对数据做CRUD的操作
         * 在ES中也是同理,我们尽量使用 ElasticsearchTemplate 对文档数据进行CRUD操作
         * 1. 属性类型(FieldType) 类型不灵活
         * 2. 主分片与副本分配数无法设置
         */
        @Test
        public void createIndexStu(){
            Stu stu = new Stu();
            stu.setStuId(1005L);
            stu.setAge(55);
            stu.setName("tom ccc");
            stu.setMoney(38.8f);
            stu.setSign("ccc is a new ccc");
            stu.setDescription("this is a ccc , a real ccc");
            IndexQuery indexQuery = new IndexQueryBuilder().withObject(stu).build();
            esTemplate.index(indexQuery);
        }
    
        /**
         * 删除索引
         */
        @Test
        public void deleteIndex(){
            esTemplate.deleteIndex(Stu.class);
        }
    
    

    3.2 文档操作

     /**
         * 更新文档
         */
        @Test
        public void updateStuDoc() {
            Map<String, Object> sourceMap = new HashMap<>();
            sourceMap.put("sign", "you see you look");
            sourceMap.put("money", 1001f);
            sourceMap.put("age", 20);
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.source(sourceMap);
            UpdateQuery updateQuery = new UpdateQueryBuilder()
                    .withClass(Stu.class)
                    .withId("1002")
                    .withIndexRequest(indexRequest)
                    .build();
            // update stu set sign = 'aaa' ,age=11.money=33 where id = '1002'
            esTemplate.update(updateQuery);
        }
    
        /**
         * 查询文档
         */
        @Test
        public void getStuDoc() {
            GetQuery query = new GetQuery();
            query.setId("1002");
            Stu stu = esTemplate.queryForObject(query, Stu.class);
            System.out.println(stu);
        }
    
        /**
         * 删除文档
         */
        @Test
        public void deleteStuDoc() {
           esTemplate.delete(Stu.class, "1002");
        }
    
    

    3.3 查询操作

     /**
         * 分页查询文档
         */
        @Test
        public void searchStuDoc() {
            Pageable pageable = PageRequest.of(0, 10);
            SearchQuery query = new NativeSearchQueryBuilder()
                     .withQuery(QueryBuilders.matchQuery("description","see you"))
                     .withPageable(pageable)
                     .build();
    
            AggregatedPage<Stu> pageStu = esTemplate.queryForPage(query, Stu.class);
            System.out.println("检索分页总数:" + pageStu.getTotalPages());
            for (Stu stu : pageStu.getContent()) {
                System.out.println(stu);
            }
        }
    
        /**
         * 分页查询文档 -- 并高亮
         */
        @Test
        public void highlightStuDoc() {
            String preTage = "<font color='red'>";
            String postTage = "</font>";
            Pageable pageable = PageRequest.of(0, 10);
            SortBuilder<FieldSortBuilder> sortBuilderMoney = new FieldSortBuilder("money").order(SortOrder.DESC);
            SortBuilder<FieldSortBuilder> sortBuilderAge = new FieldSortBuilder("age").order(SortOrder.DESC);
            SearchQuery query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.matchQuery("description","a"))
                    .withHighlightFields(new HighlightBuilder.Field("description").preTags(preTage).postTags(postTage))
                    .withPageable(pageable)
                    .withSort(sortBuilderMoney)
                    .withSort(sortBuilderAge)
                    .build();
    
            AggregatedPage<Stu> pageStu = esTemplate.queryForPage(query, Stu.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
                    List<Stu> highlightStuList = new ArrayList<>();
                    SearchHits hits = response.getHits();
                    for (SearchHit hit : hits) {
                        HighlightField highlightField = hit.getHighlightFields().get("description");
                        String description = highlightField.getFragments()[0].toString();
    
                        Object stuId = (Object) hit.getSourceAsMap().get("stuId");
                        String name = (String) hit.getSourceAsMap().get("name");
                        Integer age = (Integer) hit.getSourceAsMap().get("age");
                        String sign = (String) hit.getSourceAsMap().get("sign");
                        Object money = (Object) hit.getSourceAsMap().get("money");
                        Stu highlightStu = new Stu();
    
                        highlightStu.setDescription(description);
                        highlightStu.setStuId(Long.valueOf(stuId.toString()));
                        highlightStu.setName(name);
                        highlightStu.setAge(age);
                        highlightStu.setSign(sign);
                        highlightStu.setMoney(Float.parseFloat(money.toString()));
                        highlightStuList.add(highlightStu);
                    }
                    if(highlightStuList.size() > 0) {
                        return new AggregatedPageImpl<>((List<T>)highlightStuList);
                    }
                    return null;
                }
            });
            System.out.println("检索分页总数:" + pageStu.getTotalPages());
            for (Stu stu : pageStu.getContent()) {
                System.out.println(stu);
            }
        }
    

    4 相关信息

    • 博文不易,辛苦各位猿友点个关注和赞,感谢

    相关文章

      网友评论

          本文标题:ES 整合SpringBoot配置和使用

          本文链接:https://www.haomeiwen.com/subject/bifucltx.html