es 实战 —— spring boot 中使用 Elasticsearch

mengyue 2020-06-27

一、基础配置

依赖

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

客户端配置

spring:
  elasticsearch:
    rest:
      uris: http://localhost:9200

 基于 Java Config 的配置

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {

   // 完整的配置参考 https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients.configuration
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()  
            .connectedTo("localhost:9200")
            .build();

        return RestClients.create(clientConfiguration).rest();                         
    }
}

二、元数据对象映射(objects to documents)

常用注解示例

@Data
@Document(indexName = "article_index", type = "article", shards = 5, replicas = 1, indexStoreType = "fs", refreshInterval = "-1")
public class Article implements Serializable {
    private static final long serialVersionUID = 551589397625941750L;

    @Id
    private Long id;

    private String title;

    private String abstracts;

    private String content;

    @Field(format = DateFormat.date_time, index = true, store = true, type = FieldType.Object)
    private Date postTime;

    private Long clickCount;
}

注解说明

@Document

@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface Document {

    // 索引名称(小写)
    String indexName();

    // 映射 type(弃用)
    @Deprecated
    String type() default "";

    // 使用服务端配置?(索引创建)
    boolean useServerConfiguration() default false;

    // 分区数 (索引创建)
    short shards() default 1;

    // 副本数 (索引创建)
    short replicas() default 1;

    // 刷新间隔 (索引创建)
    String refreshInterval() default "1s";

    // 索引存储类型 (索引创建)
    String indexStoreType() default "fs";

    // 是否在启动时创建索引
    boolean createIndex() default true;

    //Configuration of version management.
    VersionType versionType() default VersionType.EXTERNAL;
}

@Field

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface Field {

    // 默认为 Java Field 名称
    String name() default "";

    // 具体参考 https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html
    FieldType type() default FieldType.Auto;

    boolean index() default true;

    // format 与 pattern 用于定义日期类型
    DateFormat format() default DateFormat.none;

    String pattern() default "";

    // 是否独立存储,不需要从 _source 解析,在需要频繁使用某个字段时使用。
    boolean store() default false;

    // 索引时分析器
    String analyzer() default "";

    // 查询时分析器
    String searchAnalyzer() default "";

    // 跟 analyzer 类似,只对 keyword 类型的字段有效,只有 char_filter和filter,没有tokenizer
    String normalizer() default "";
}

233

相关推荐