动态的为ElasticSearch的@Document指定index
前言
由于项目定义了配置中心,分了开发库,测试库,预生产,每次发布都需要改项目中所定义的常量,希望动态为Document指定IndexName,找了好久,终于找到。
第一种,直接定义一个实体类
@Value("${etrali.indexname}")
private String indexName;
@Bean
public String indexName(){
return indexName;
}
在你的ElasticSearch配置实体类中定义,注意这里后面的type也可以改为动态的。
@Document(indexName="#{@indexName}",type = "syslog_watcher")
第二种。配置文件定义索引和类型,注入到实体中
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;
之后就可以接收返回了
贴上application.yml上面的配置
###定义 es 的索引和类型
index.name.salegoods.new=index_sale_goods_new
index.type.salegoods.new=type_sale_goods_new
使用
/**
* termQuery : 完全匹配一个词语
* queryStringQuery : 查询解析查询字符串(搜索范围是全部字段)
* must : 跟AND 一样的
* should : 跟OR 一样
*/
public void getSaleGoodsList(){
String appId = "10000";
String key = "000";
QueryBuilder appIdKey = QueryBuilders.termQuery("appId", appId);
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(key);
QueryBuilder query = QueryBuilders.boolQuery().must(queryBuilder).must(appIdKey);;
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
// 定义查询
Iterable<SaleGoodsElastic> list= elasticsearchTemplate.queryForPage(searchQuery ,SaleGoodsElastic.class);
}
借鉴网址: