SpringData集成ES7.3

  • 操作 ES 可以采用 SpringDataElasticSearch
  • 使用 intellij IDEA 创建一个 Maven jar 工程
  • 我这里就不在贴图了自行创建

添加相关依赖

  • 修改 pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

添加相关配置文件

  • src/java/resources 中创建 application.yml
  • 配置内容如下:
spring:
  elasticsearch:
    rest:
      uris: http://139.196.183.130:9200

添加相关实体类

  • top.it6666.dao 下创建一个 Article 实体类,内容如下:
/**
 * @author BNTang
 **/
@Data
@Document(indexName = "article")
public class Article {

    @Id
    private String id;

    @Field(store = true, type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String title;

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

    @Field(store = true, type = FieldType.Integer)
    private Integer read;

    @Field(store = true, type = FieldType.Keyword)
    private String types;

    @Field(store = true, type = FieldType.Keyword)
    private String author;
}
  • Spring Data 通过注解来声明字段的映射属性
  • 有下面的三个注解来完成的:
注解名称 作用
@Document 标记实体类为文档对象
@Id 标记一个字段作为主键
@Field 标记为文档中的那个的字段进行映射

相关注解详解

@Document

  • 标记在类上,标记实体类为文档对象,一般有四个属性,如下:
  • indexName:对应索引库的名称,指定那个索引
  • type:索引的类型
  • shards:分片数量,默认为 5
  • replicas:副本数量,默认为 1

@Id

  • 标记在成员变量上,标记一个字段作为 id主键

@Field

  • 标记在成员变量上,标记为文档中的那个的字段,并指定字段映射属性:
  • type:字段类型,取值是 枚举:FieldType
  • index:是否索引,布尔类型,默认是 true
  • store:是否存储,布尔类型,默认是 false
  • analyzer:分词器名称:ik_max_word
  • searchAnalyzer:搜索时的分词器名称

Dao层

  • top.it6666.mapper 中创建一个 ArticleDao 接口
/**
 * @author BNTang
 **/
public interface ArticleDao extends ElasticsearchRepository<Article, String> {
}

Service层

  • top.it6666.service 中创建一个 ArticleService 类如下:
/**
 * @author BNTang
 */
@Service
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
}
posted @ 2020-10-20 17:28  BNTang  阅读(472)  评论(0编辑  收藏  举报