spring集成elasticsearch并实现基础功能

什么是elasticsearch?

  Elasticsearch 是一个基于 Lucene 的开源搜索引擎和分析引擎,它为结构化和非结构化的海量数据提供了实时的搜索、分析和可视化功能。Elasticsearch 是 Elastic Stack(也称为 ELK Stack)的核心组件之一,其他组件还包括 Kibana(用于数据可视化)、Logstash(用于数据收集和处理)。

es 主要是对数据进行搜索,分析,倒排。是一个开源的高扩展的分布式全文搜索引擎。近实时的搜索。

es 的特点:

1、搜索的数据对象大量的非结构化的文本

2、倒排索引

3、每个字段都可以被索引和搜索

docker拉取es镜像

yum install -y yum-utils device-mapper-persistent-data lvm2

docker search elasticsearch

docker pull elasticsearch:7.3.1

docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node"  -e ES_JAVA_OPTS="-Xms1024m -Xmx1024m" 3d3aa92f641f

  es中文分词插件

https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.3.1/elasticsearch-analysis-ik-7.3.1.zip

插件安装

mkdir /soft/ik

进入容器内部
docker exec -it elasticsearch /bin/bash
cd plugins
mkdir ik

回到外部
docker cp /soft/ik/. 73438a827b55:/usr/share/elasticsearch/plugins/ik

重启es

  引入依赖

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>2.4.2</version>
        </dependency>

  

 配置yml的地址

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.math.BigDecimal;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "subject_index",createIndex = false)
public class SubjectInfoEs {
    @Field(type = FieldType.Long)
    @Id
    private Long id;
    @Field(type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_smart")
    private String subjectName;
    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String subjectAnswer;
    @Field(type = FieldType.Keyword)
    private String createUser;
    @Field(type = FieldType.Date, index = false)
    private Long createTime;

}

引入继承

ElasticsearchRepository类
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfoEs;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public interface SubjectEsRepository extends ElasticsearchRepository<SubjectInfoEs, Long> {
}

  接口层

public interface SubjectEsService {
    void createIndex();
    void addDocs();

    void getDocs();

    void find();

    void search();

}

  接口实现层

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfoEs;
import com.jingdianjichi.subject.infra.basic.esRepo.SubjectEsRepository;
import com.jingdianjichi.subject.infra.basic.service.SubjectEsService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("subjectEsService")
@Slf4j
public class SubjectEsServiceImpl implements SubjectEsService {
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Resource
    private SubjectEsRepository subjectEsRepository;

    @Override
    public void createIndex() {
        IndexOperations indexOperations =
                elasticsearchRestTemplate.indexOps(SubjectInfoEs.class);
        indexOperations.create();
        Document mapping = indexOperations.createMapping(SubjectInfoEs.class);
        indexOperations.putMapping(mapping);

    }

    @Override
    public void addDocs() {
        List<SubjectInfoEs> list = new ArrayList<>();
        list.add(new SubjectInfoEs(1l, "redis是什么", "redis是·缓存", "**", new Date().getTime()));
        list.add(new SubjectInfoEs(2l, "mysql是什么", "mysql是数据库", "**", new Date().getTime()));
        subjectEsRepository.saveAll(list);
    }

    @Override
    public void getDocs() {

    }

    @Override
    public void find() {
        subjectEsRepository.findAll().forEach(subjectInfoEs -> {
            log.info("subjectInfoEs:{}", JSON.toJSONString(subjectInfoEs));
        });

    }

    @Override
    public void search() {
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("subjectName", "redis"))
                .build();
        SearchHits<SubjectInfoEs> search = elasticsearchRestTemplate.
                search(nativeSearchQuery, SubjectInfoEs.class);
        List<SearchHit<SubjectInfoEs>> searchHits = search.getSearchHits();
        log.info("searchHits:{}", JSON.toJSONString(searchHits));

    }
}

  controller层

  @GetMapping("testCreateIndex")
    public void testCreateIndex() {
        subjectEsService.createIndex();
    }
    @GetMapping("addDocs")
    public void addDocs() {
        subjectEsService.addDocs();
    }
    @GetMapping("search")
    public void search() {
        subjectEsService.search();
    }
    @GetMapping("find")
    public void find() {
        subjectEsService.find();
    }

   索引成功创建并且添加文档

search以及find方法日志打印完成

22:43:06.848  [http-nio-3001-exec-1] INFO  
SubjectEsServiceImpl - searchHits:[{"content":{"createTime":1722522746532,"createUser":"**","id":1,"subjectAnswer":"redis是·缓存","subjectName":"redis是什么"},"highlightFields":{},"id":"1","index":"subject_index","innerHits":{},"score":0.6931472,"sortValues":[]}]
22:43:45.486  [http-nio-3001-exec-4] INFO  
SubjectEsServiceImpl - subjectInfoEs:{"createTime":1722522746532,"createUser":"**","id":1,"subjectAnswer":"redis是·缓存","subjectName":"redis是什么"}
22:43:45.486  [http-nio-3001-exec-4] INFO  
SubjectEsServiceImpl - subjectInfoEs:{"createTime":1722522746532,"createUser":"**","id":2,"subjectAnswer":"mysql是数据库","subjectName":"mysql是什么"}

  

posted @ 2024-08-01 22:57  橘子味芬达水  阅读(49)  评论(0编辑  收藏  举报