通过自定义枚举实现构建elasticsearch索引

注意:该代码是建立在ES7.0以上,如果版本不一致,请参考官网修改创建映射那部分代码。

枚举类:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

    String indexName();

    String type() default "";

    short shards() default 5;

    short replicas() default 1;

    String refreshInterval() default "1s";

    String indexStoreType() default "fs";

    boolean createIndex() default true;

}
package com.voice.elastics.model.annotation;

import com.voice.elastics.model.enums.FieldType;
import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ElementType.FIELD})
@Retention(RUNTIME)
@Documented
public @interface ESField {

    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    FieldType type() default FieldType.Keyword;

    boolean index() default true;

    String pattern() default "";

    boolean store() default false;

    boolean fielddata() default false;

    String searchAnalyzer() default "";

    String analyzer() default "";

    String normalizer() default "";

    String[] ignoreFields() default {};

    boolean includeInParent() default false;

    String[] copyTo() default {};
}
public enum FieldType {
    Text,
    Byte,
    Short,
    Integer,
    Long,
    Date,
    Half_Float,
    Float,
    Double,
    Boolean,
    Object,
    Auto,
    Nested,
    Ip,
    Attachment,
    Keyword;

    private FieldType() {
    }
}

在实体类上添加自定义枚举

package com.voice.elastics.model;

import com.voice.elastics.model.annotation.Document;
import com.voice.elastics.model.annotation.ESField;
import com.voice.elastics.model.enums.DictDataEnum;
import com.voice.elastics.model.enums.FieldType;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author salted fish
 * @Date 2020/11/17
 */
@Data
@Document(indexName = "t_record_interface")
public class RecordInterface {

    private static Logger log = LoggerFactory.getLogger(RecordInterface.class);
    /**
     * 唯一主键
     */
    @ESField(type = FieldType.Long)
    private Integer id;

    /**
     * 接口调用时间
     */
    @ESField(type = FieldType.Date)
    private Date createTime;

    /**
     * 0自身黑名单或记录命中,1外部黑名单命中
     */
    @ESField(type = FieldType.Long)
    private Integer blackModel;

    /**
     * 0失败,1成功
     */
    @ESField(type = FieldType.Long)
    private Integer result;



}

使用工具类加反射机制,构建你的索引

package com.voice.elastics.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.voice.elastics.model.annotation.Document;
import com.voice.elastics.model.annotation.ESField;
import com.voice.elastics.model.enums.FieldType;
import org.apache.http.client.utils.DateUtils;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author salted fish
 * @Date 2021/5/8
 */
@Component
public class ESUtil {

    private Logger logger = LoggerFactory.getLogger(ESUtil.class);

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     */
    public <T> void createIndex(T t) throws Exception {
        Document document = t.getClass().getAnnotation(Document.class);
        if (Objects.isNull(document)) {
            throw new RuntimeException("Document缺失, 无法创建索引");
        }

        String indexName = document.indexName();
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        fillIndex(request, document);
        setMapping(request, t);
        CreateIndexResponse result = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        if (result.isAcknowledged()) {
            logger.info("创建索引成功,索引名称: " + indexName);
        } else {
            logger.error("创建索引失败,索引名称: " + indexName);
        }
    }

    /**
     * 创建映射 startObject== {   endObject== }
     */
    private  <T> void setMapping(CreateIndexRequest request, T t) throws Exception {
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject();
        mapping.startObject("properties");
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            ESField esField = field.getAnnotation(ESField.class);
            if (Objects.nonNull(esField)) {
                mapping.startObject(field.getName())
                        .field("type", esField.type().name().toLowerCase())
                        .field("store", esField.store());
               if (StringUtils.isNotBlank(esField.searchAnalyzer())) {
                    mapping.field("search_analyzer", esField.searchAnalyzer());
                }
                if (StringUtils.isNotBlank(esField.analyzer())) {
                    mapping.field("analyzer", esField.analyzer());
                }

                mapping.endObject();
            }

        }
        mapping.endObject().endObject();
        request.mapping(mapping);
    }

    /**
     * 填充索引参数
     */
    private void fillIndex(CreateIndexRequest request, Document document) {
        request.settings(Settings.builder().put("index.number_of_shards", document.shards())
                .put("index.number_of_replicas", document.replicas())
                .put("index.refresh_interval", document.refreshInterval())
                /*.put("index.index_store_type", document.indexStoreType())*/);
    }


}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Elasticsearch是一个开源的分布式搜索和分析引擎,用于处理大规模数据集的实时搜索和分析。它基于Lucene库构建而成,提供了强大的全文搜索、分布式性能和可扩展性。 在简单运用Elasticsearch之前,你需要先安装和配置Elasticsearch。安装完成后,你可以使用Elasticsearch提供的RESTful API进行索引数据、搜索和聚合操作。 下面是一个简单的例子,演示如何使用Elasticsearch进行索引和搜索操作: 1. 导入Elasticsearch客户端库(例如elasticsearch-py): ```python from elasticsearch import Elasticsearch ``` 2. 创建Elasticsearch客户端实例: ```python es = Elasticsearch('http://localhost:9200') ``` 3. 创建索引: ```python index_name = 'my_index' mapping = { "properties": { "title": {"type": "text"}, "content": {"type": "text"} } } es.indices.create(index=index_name, body={"mappings": mapping}) ``` 4. 索引文档: ```python document = { "title": "Elasticsearch Introduction", "content": "Elasticsearch is a distributed search engine." } es.index(index=index_name, body=document) ``` 5. 搜索文档: ```python query = { "query": { "match": {"content": "distributed"} } } result = es.search(index=index_name, body=query) print(result['hits']['hits']) ``` 以上是一个简单的示例,演示了如何使用Elasticsearch进行索引和搜索操作。你可以根据自己的需求进一步深入学习和了解Elasticsearch的其他功能和用法。 关于枚实现单例模式的问题,你可以使用Python中的枚(Enum)来实现单例模式。以下是一个示例: ```python from enum import Enum class Singleton(Enum): INSTANCE = 1 # 使用方式 instance = Singleton.INSTANCE ``` 在这个示例中,我们定义了一个枚类Singleton,它只有一个枚成员INSTANCE。通过访问INSTANCE成员,我们可以获取到单例对象的实例。 需要注意的是,Python的枚类并不是传统意义上的单例模式,它只是提供了一种简洁明了的方式来实现单例。如果你需要更复杂的单例模式实现,可以考虑使用装饰器、元类或其他方式来实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值