spring boot整合mybatis+elasticsearch

发布于:2025-02-26 ⋅ 阅读:(17) ⋅ 点赞:(0)

1.POM.XML导入包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<!--            <exclusions>-->
<!--                &lt;!&ndash; 排除 Spring Boot 3.x 默认的 ES 8.x 客户端 &ndash;&gt;-->
<!--                <exclusion>-->
<!--                    <groupId>org.elasticsearch.client</groupId>-->
<!--                    <artifactId>elasticsearch-java</artifactId>-->
<!--                </exclusion>-->
<!--            </exclusions>-->
        </dependency>

<!--        <dependency>-->
<!--            <groupId>co.elastic.clients</groupId>-->
<!--            <artifactId>elasticsearch-java</artifactId>-->
<!--            <version>${elasticsearch.version}</version>-->
<!--        </dependency>-->

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

2.application.yml增加配置

spring:
  elasticsearch:
    uris: http://127.0.0.1:9200
    connection-timeout: 15s
    socket-timeout: 15s
    headers:
      Accept: application/vnd.elasticsearch+json; compatible-with=7 #springboot3兼容es7.17.X
      Content-Type: application/vnd.elasticsearch+json; compatible-with=7 #springboot3兼容es7.17.X

3.elasticsearch版本

elasticsearch-7.17.5下载地址

linux启动

cd elasticsearch-7.17.5/bin

./elasticsearch

 

4.java代码 

对象

@Document(indexName = "search_global_index")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SearchGlobalEsPo {

    @Id
    private String id;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String name;

    @Field(type = FieldType.Long)
    private Long souId;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String tableName;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String content;

    @Field(type = FieldType.Text)
    private String description;
}

dao层

public interface SearchGlobalEsMapper extends ElasticsearchRepository<SearchGlobalEsPo, Long> {
}

service层

@Service
@RequiredArgsConstructor
public class SearchGlobalServiceImpl implements SearchGlobalService {

    private final SearchGlobalEsMapper searchGlobalEsMapper;

//    private final RestHighLevelClient restHighLevelClient;

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void add(SearchGlobalCmdAddBo cmdBo) {
        SearchGlobalEsPo esPo = MapstructUtils.convert(cmdBo, SearchGlobalEsPo.class);
        esPo.setId(IdUtils.randomUUID());
        searchGlobalEsMapper.save(esPo);
    }

    @Override
    public List<SearchGlobalVo> list() {
        Iterable<SearchGlobalEsPo> iterable = searchGlobalEsMapper.findAll();
        List<SearchGlobalVo> vos = new ArrayList<>();
        Iterator<SearchGlobalEsPo> iterator = iterable.iterator();
        while (iterator.hasNext()){
            SearchGlobalVo vo = MapstructUtils.convert(iterator.next(), SearchGlobalVo.class);
            vos.add(vo);
        }
        return vos;
    }

//    @Override
//    public List<SearchGlobalVo> search(String keyword) {
//        SearchRequest searchRequest = new SearchRequest("search_global_index");
//        //大多数搜索参数都添加到SearchSourceBuilder中。它为进入搜索请求主体的所有内容提供了setter。
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("content", keyword);
//        matchQueryBuilder.fuzziness(Fuzziness.AUTO); //开启模糊性查询
//        matchQueryBuilder.prefixLength(3); //模糊前缀
//        matchQueryBuilder.maxExpansions(10); //设置最大扩展选项
        searchSourceBuilder.query(QueryBuilders.matchQuery("content",keyword));
//        searchSourceBuilder.query(matchQueryBuilder);
//        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//        searchRequest.source(searchSourceBuilder);
//        try {
//            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//            SearchHit[] hits = search.getHits().getHits();
//            for (SearchHit hit : hits) {
//                System.out.println(hit);
//
//            }
//        } catch (IOException e) {
//        }
//        return List.of();
//    }


    @Override
    public TableDataInfo<SearchGlobalVo> search(String keyword, Pageable pageable) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.multiMatchQuery(keyword, "name", "content"))
            .withHighlightFields(
                new HighlightBuilder.Field("name").preTags("<em>").postTags("</em>"),
                new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
            )
            .withPageable(pageable)
            .build();

        SearchHits<SearchGlobalEsPo> searchHits = elasticsearchRestTemplate.search(searchQuery, SearchGlobalEsPo.class);
        List<SearchGlobalVo> vos = new ArrayList<>();
        searchHits.forEach(hit -> {
            SearchGlobalVo vo = MapstructUtils.convert(hit.getContent(), SearchGlobalVo.class);
            vos.add(vo);
        });
        TableDataInfo<SearchGlobalVo> tableDataInfo = new TableDataInfo(vos, searchHits.getTotalHits());
        tableDataInfo.setCode(200);
        return tableDataInfo;
    }

    @Override
    public R<Void> update(SearchGlobalCmdUpdateBo cmdUpdateBo) {
        Optional<SearchGlobalEsPo> searchGlobalEsPo = searchGlobalEsMapper.findById(cmdUpdateBo.getId());
        if(searchGlobalEsPo.isEmpty()){
            return R.fail("数据不存在,不能进行修改");
        }
        searchGlobalEsMapper.save(MapstructUtils.convert(cmdUpdateBo, searchGlobalEsPo.get()));
        return R.ok();
    }

    @Override
    public R<Void> delete(String id) {
        searchGlobalEsMapper.deleteById(id);
        return R.ok();
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到