server:
port: 8073
spring:
profiles:
active: dev
thymeleaf:
cache: false
mybatis-plus:
mapper-locations: classpath*:/mapper
@Slf4j
@RestController
@RequestMapping("/es")
public class EsController {
@Autowired
private LibraryService libraryService;
@Autowired
private EsService esService;
@GetMapping("/save")
public ResultBody getEs() throws IOException {
log.info(".............");
Map map = libraryService.saveToEs();
System.err.println(JSON.toJSONString(map));
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
String uri = request.getRequestURI();
return ResultBody.ok().path(uri).data(libraryService.testEsRepo());
}
@GetMapping("/sel/{name}")
public ResultBody selName(@PathVariable("name") String name) throws IOException {
log.info(".............");
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
String uri = request.getRequestURI();
return ResultBody.ok().path(uri).data(libraryService.selName(name));
}
@GetMapping("/client")
public ResultBody selClient() throws IOException {
log.info(".............");
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
String uri = request.getRequestURI();
return ResultBody.ok().path(uri).data(esService.findByAannualRevenue());
}
}
3.2 Service:
package com.ghj.demoes.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ghj.demoes.dao.LibraryEntityMapper; import com.ghj.demoes.dao.LibraryMapper; import com.ghj.demoes.form.TaxParam; import com.ghj.demoes.pojo.Library; import com.ghj.demoes.pojo.LibraryEntity; import com.ghj.demoes.service.LibraryService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.unit.Timevalue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @Slf4j @Service @Transactional(rollbackFor = Exception.class) public class LibraryServiceImpl extends ServiceImpl3.3 Dao Entityimplements LibraryService { @Autowired private LibraryMapper LibraryMapper; @Autowired private LibraryEntityMapper LibraryEntityMapper; @Autowired @Qualifier("restHighLevelClient") private RestHighLevelClient client; @Override public Map saveToEs() throws IOException { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.lambda() .isNotNull(Library::getId); List libraryList = libraryMapper.selectList(queryWrapper); System.err.println(JSON.toJSONString(libraryList)); // 批量导入es库。 BulkRequest bulkRequest = new BulkRequest(); bulkRequest.timeout("10s"); // 批处理请求。 for (int i = 0; i < libraryList.size(); i++) { LibraryEntity libraryEntity = new LibraryEntity(); BeanUtils.copyProperties(libraryList.get(i),libraryEntity); libraryEntity.setAnnualRevenue(JSONArray.parseArray (libraryList.get(i).getAnnualRevenue(), TaxParam.class)); libraryEntity.setRdDeductible(JSONArray.parseArray (libraryList.get(i).getRdDeductible(),TaxParam.class)); bulkRequest.add( new IndexRequest("demo_test") .source(JSON.toJSONString(libraryEntity), XContentType.JSON) ); } BulkResponse bulkResp = client.bulk(bulkRequest, RequestOptions.DEFAULT); System.err.println(bulkResp.hasFailures()); // 是否失败,返回false 代表成功。 Map resMap = new HashMap<>(); if (false == bulkResp.hasFailures()){ resMap.put("mes","save to es succ..."); }else { resMap.put("mes","save to es failed..."); } return resMap; } @Override public List selName(String name) { Map map = new HashMap<>(); map.put("year",name); org.springframework.data.elasticsearch.core.SearchHits libraryEntities = libraryEntityMapper.selsss(map); System.err.println(JSON.toJSONString(LibraryEntities)); List re = libraryEntityMapper.findByName("派"); System.err.println(JSON.toJSONString(re)); //得到查询返回的内容 List searchHits = libraryEntities.getSearchHits(); //设置一个最后需要返回的实体类集合 List entities = new ArrayList<>(); //遍历返回的内容进行处理 for(org.springframework.data.elasticsearch.core.SearchHit searchHit:searchHits){ System.out.println(JSON.toJSONString(searchHit.getContent())); entities.add(JSONObject.parseObject(JSON.toJSONString( searchHit.getContent()), LibraryEntity.class)); //高亮的内容 Map highlightFields = searchHit.getHighlightFields(); } return entities; } @Override public SearchResponse findByAannualRevenue() throws IOException { // 创建BoolQueryBuilder BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); // 子查询“且”关系 BoolQueryBuilder childBoolQueryBuilder = new BoolQueryBuilder() .must(QueryBuilders.nestedQuery("annualRevenue", QueryBuilders.boolQuery() .must(QueryBuilders.matchQuery("annualRevenue.year","2019")), ScoreMode.None) ); BoolQueryBuilder childBoolQueryBuilder2 = new BoolQueryBuilder() .must(QueryBuilders.nestedQuery("annualRevenue", QueryBuilders.boolQuery() .must(QueryBuilders.matchQuery("annualRevenue.val","73")), ScoreMode.None) ); BoolQueryBuilder childBoolQueryBuilder3 = new BoolQueryBuilder() .must(QueryBuilders.nestedQuery("annualRevenue", QueryBuilders.boolQuery() .must(QueryBuilders.rangeQuery("annualRevenue.val").gt(30).lte(90)), ScoreMode.None) ); boolQueryBuilder.must(childBoolQueryBuilder); boolQueryBuilder.must(childBoolQueryBuilder2); boolQueryBuilder.must(childBoolQueryBuilder3); // 创建SearchSourceBuilder SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 查询条件生成DSL语句 searchSourceBuilder.query(boolQueryBuilder); // 从多少 searchSourceBuilder.from(0); // 查多少条数据,如果设置“0”返回count数量 searchSourceBuilder.size(50); // 排序规则 searchSourceBuilder.sort("createTime", SortOrder.DESC); // 设置超时 Timevalue t=new Timevalue(3000); searchSourceBuilder.timeout(t); SearchRequest searchRequest = new SearchRequest("demo_test"); searchRequest.source(searchSourceBuilder); SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT); System.out.println("search total:" + searchResp.getHits().getTotalHits().value); return searchResp; } }
package com.ghj.demoes.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.ghj.demoes.form.TaxParam;
import lombok.*;
import org.springframework.data.elasticsearch.annotations.document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@document(indexName = "demo_test")
public class LibraryEntity implements Serializable {
@TableId(type = IdType.ID_WORKER_STR)
private String id;
// 企业名称
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String name;
// 企业地址
@Field(type = FieldType.Text,analyzer = "douhao",searchAnalyzer = "douhao")
private String registerAddress;
// 对应各表的主键id。
@Field(type = FieldType.Keyword)
private String uniqueId;
// 年收
@Field(type = FieldType.Nested)
private List annualRevenue;
// 其他费用
@Field(type = FieldType.Nested)
private List rdDeductible;
}
TaxParam.java
package com.ghj.demoes.form;
import lombok.*;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public class TaxParam {
@Field(type = FieldType.Keyword)
private String year;
// 区域,逗号分词。
@Field(type = FieldType.Integer)
private Integer val;
}
Dao
package com.ghj.demoes.dao; import com.ghj.demoes.pojo.LibraryEntity; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.awt.print.Pageable; import java.util.List; import java.util.Map; @Repository public interface LibraryEntityMapper extends ElasticsearchRepository3.4 ES结构{ List findByName(String name); List findByRegisterAddress(String address); @Query("{"bool": {"must": [{"nested": {"path": "annualRevenue","query": {"bool": {n" + " "must": [{"match": {"annualRevenue.year": "?0"}}],n" + " "filter":{"script":{"script":{"source":"73 <= doc['annualRevenue.val'].value && doc['annualRevenue.val'].value < 75"}}}}}}}]}}") SearchHits selOne(String year); @Query("{"bool": {"must": [{"nested": {"path": "annualRevenue","query": {"bool": {"must": n" + "[{"match": {"annualRevenue.year": "?0"}},n" + "{"range":{"annualRevenue.val":{"gte":23,"lte":120}}}n" + "]}}}}]}}") SearchHits selSecond(String year); }
{
"demo_test": {
"mappings": {
"basic": {
"properties":{
"name":{
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"registerAddress": {
"type": "text",
"store": true,
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"uniqueId": {
"type": "keyword",
"store": true
},
"annualRevenue": {
"type": "nested"
},
"rdDeductible": {
"type": "nested"
}
}
}
}
}
}
4.启动项目,可测试。
备注:删除与更新自己写,随便用哪种方式。
over。


