动态的为ElasticSearch的@Document指定index

一、实体类索引注解说明:

@Document(indexName = "user_db", type = "user_table")
public class User{
    @Id
    @Field(type = FieldType.Keyword)
    private String userId;

    @Field(type= FieldType.Keyword)
    private String account; 

    @Field(type= FieldType.Keyword)
    private String userName;

    @Field(type= FieldType.Keyword)
    private String idCard; 

    @Field(type = FieldType.Date,
            format = DateFormat.custom,
            pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime; 
    //DOTO
    //get和set方法
    //toString()方法
}

在你的ElasticSearch配置实体类中定义

IndexName是可以动态指定的。7以前不用加@,7之后必须加@才能识别动态的。

@Document(indexName="#{@indexName}",type = "syslog_watcher")

可以直接@Value("${es.indexname}")

@Value("${es.indexname}")
private String indexName;
 
@Bean
public String indexName(){
    return indexName;
}

第二种。配置文件定义索引和类型,注入到实体中

1、在配置文件中定义好你们的index和type

2、创建配置Bean,使用@Named或者@Component

@Component
public class EsAttribute {
    // 商品详情的索引名
    @Value("${index.name.salegoods.new}")
    private String indexSaleGoodsNew;
 
    // 商品详情索引中的type名
    @Value("${index.type.salegoods.new}")
    private String typeSaleGoodsNew;
    ...这里我没把setting和getting,避免太长
}

之后在ElasticSearch返回的类型中使用(注:这里博主使用的是定义一个实体存放到Elasticsearch中,所以需要用实体接收)

/**
 *  FieldIndex.not_analyzed:不会分词,只能根据原词索引Field;
 *  FieldIndex.analyzed:根据分词器分词,可以根据原词和分词后的词条索引Field;
 *  FieldIndex.no:该字段不会被索引,查不到;
 */
@Document(indexName = "#{@esAttribute.indexSaleGoodsNew}", type = "#{esAttribute.typeSaleGoodsNew}")
public class SaleGoodsElastic {
    // ID
    @Id
    @Field(type = FieldType.String)
    private String saleGoodsId; 
 
    // 名称
    @Field(type = FieldType.String, index = FieldIndex.analyzed)
    private String name;
 
    // 状态
    @Field(type = FieldType.Integer)
    private Integer status;
 
    // 商品所属企业id
    @Field(type = FieldType.String ,index = FieldIndex.not_analyzed)
    private String organizationId;
 
    // 商品所属企业名称
    @Field(type = FieldType.String, index = FieldIndex.analyzed)
    private String organizationName;
 
    // 商品创建时间
    @Field(type = FieldType.Date)
    private Date createTime;
 
    // 商品价格
    @Field(type = FieldType.Integer)
    private Integer price;
 
    // 商品所属目录id
    @Field(type = FieldType.String ,index = FieldIndex.not_analyzed)
    private String goodsContentsId;
 
    // 商品所属目录名称
    private String contentsName;
 
    // 商品的属性列表
    private List<GoodsAttrElastic> goodsAttrElasticList;
 
    // 商品所属店铺列表
    private List<ShopElastic> shopElasticList;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值