- 操作 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
      urishttp//139.196.183.1309200添加相关实体类
- 在top.it6666.dao 下创建一个Article 实体类,内容如下:
/**
 * @author BNTang
 **/
(indexName = "article")
public class Article {
    
    private String id;
    (store = true, type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String title;
    (store = true, type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String content;
    (store = true, type = FieldType.Integer)
    private Integer read;
    (store = true, type = FieldType.Keyword)
    private String types;
    (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
 */
public class ArticleService {
    
    private ArticleDao articleDao;
}









