spring整合es:
<elasticsearch:transport-client id="client" cluster-nodes="${elasticsearch_cluster_nodes}" cluster-name="${elasticsearch_cluster_name}" />//对应es.properties中的数据 <bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <constructor-arg ref="client" /> </bean>其实就是
ElasticsearchTemplate类对javaAPI的客户端类进行了封装
导入、注入ElasticsearchTemplate
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;//导入包 @Autowired(required=false) private ElasticsearchTemplate esTemplate;
新增或者更新数据到ES
//增加或者更新 public ReturnResult addEsCashInfo(String cashId, String type) throws Exception { ReturnResult result = new ReturnResult(); if (StringUtils.isBlank(cashId)) { String msg = "cashId不能为空"; logger.info(msg); throw new GmallException(msg); } logger.info("addEsCashInfo cashId=" + cashId + ",type=" + type); net.sf.json.JSONObject obj = new net.sf.json.JSONObject(); if (SuperAppConstant.CASH_CALL_BACK_TYPE.equals(type)) { Cash cash = cashMapper.selectByPrimaryKey(cashId); obj = net.sf.json.JSONObject.fromObject(cash); CashEs cashEs = new CashEs(); BeanUtils.copyProperties(cashEs, cash); IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(SuperAppConstant.ES_INDEX_NAME) .withType(SuperAppConstant.ES_CASH_TYPE).withId(cashId).withObject(cashEs).build(); esTemplate.index(indexQuery); }else{ String msg = "未知支付类型"; logger.info(msg); throw new GmallException(msg); } result.setCode(ReturnCodeType.SUCCESS).setMessage("插入成功"); return result; }
项目使用esTemplate方法:
https://docs.spring.io/spring-data/elasticsearch/docs/current/api/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.html
count,scan,scroll,putMapping(Create mapping for a class),refresh(refresh the index),各种query
查询参数:NativeSearchQueryBuilder(例如拼接列表页关键字)
es映射:
为了能将日期视为日期,数字视为数字,字符串视为全文或精确值字符串,es需要知道每个字段包含的数据类型,即映射。映射定义了类型中的字段,每个字段的数据类型以及Elasticsearch应该如何处理该字段。映射也用于配置与类型关联的元数据。
- 串:
string
- 整数:
byte
,short
,integer
,long
- 浮点:
float
,double
- 布尔:
boolean
- 日期:
date
可自定义映射
查看映射 GET /gb/_mapping/tweet
Spring-data-elasticsearch
ElasticsearchRepository
是Spring提供的操作ElasticSearch的数据层,封装了大量的基础操作,通过它可以很方便的操作ElasticSearch的数据。
BoolQueryBuilder:用来封装查询条件
clazz.isAnnotationPresent(Document.class):用来判断clazz上有没有Document注解
setPersistentEntityIndexAndType(query, clazz);用于给查询条件指定要查询的索引和类型
例如:
@Document(indexName = ElasticSearchConfig.INDEX_NAME, type = ElasticSearchConfig.TYPE_STATICDATAS) @Mapping(mappingPath = ElasticSearchConfig.MAPPING_PATH) public class StaticDataModel extends PageModel {