一、前言
elasticsearch安装就不做过多介绍了,网上一搜一大堆;最需要注意的就是Elasticsearch与spring版本,防止版本不兼容导致的后续的一系列问题。我这里springboot+spring-data-elasticsearch,他们的版本对照关系可以参照spring-data-elasticsearch官网版本对照。
二、jar依赖及配置
- pom.xml
<!--springboot版本-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.5.12</version>
</dependency>
<!--spring-data-elasticsearch版本-->
<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-elasticsearch</artifactId><version>4.2.10</version>
</dependency>
- application.yml
spring:elasticsearch:rest:uris: **username: **password: **
三、代码实现
3.1 实体类
@Document:对应一个文档记录
indexName:指定索引名称
@Id:用来将对象中id和ES中_id映射
@Field:用来指定ES中的字段对应Mapping
type:用来指定ES中存储类型
analyzer:用来指定使用哪种分词器
@Data
@Document(indexName = "user")
public class User {@Idprivate String id;@Field(type = FieldType.Text, analyzer = "ik_max_word")private String name;@Field(type = FieldType.Date)private Date bir;@Field(type = FieldType.Text,analyzer = "ik_max_word")private String content;
}
3.2 业务代码
@Service
public class EsService {@Autowiredprivate ElasticsearchRestTemplate restTemplate;/*** 初始化es序列*/public boolean initIndex() {IndexOperations indexOperations = restTemplate.indexOps(User.class);if (!indexOperations.exists()) {indexOperations.create();Document mapping = indexOperations.createMapping();indexOperations.putMapping(mapping);return true;}return false;}/*** 初始化es数据**/public void initEsData() {// 查询用户叔叔List<User> list = 查询数据restTemplate.save(list);}/*** 分页查询数据** @param keyword* @param pageNo* @param pageSize* @throws IOException*/public PageInfo<User> search(String keyword, Integer pageNo, Integer pageSize) throws IOException {PageInfo<User> pageInfo = new PageInfo<>();if (pageNo <= 0) {pageNo = 1;}if (pageSize <= 0) {pageSize = 10;}pageInfo.setPageNo(pageNo);pageInfo.setPageSize(pageSize);// 分页数据PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "bir");// 高亮字段HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false).fragmentSize(30).preTags("<span style='color:#799ed9'>").postTags("</span>");// 查询条件QueryStringQueryBuilder queryBuilder = null;if (StringUtils.isNotBlank(keyword)) {keyword = QueryParser.escape(keyword);keyword = "\"" + keyword + "\"";queryBuilder = QueryBuilders.queryStringQuery(keyword).field("name").field("content").analyzer("ik_max_word");}NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(queryBuilder).withPageable(pageRequest).withHighlightBuilder(highlightBuilder).build();SearchHits<User> searchHits = restTemplate.search(query, User.class);long totalHits = searchHits.getTotalHits();if (totalHits <= 0) {return pageInfo;}pageInfo.setCount(totalHits);List<User> list = new ArrayList<>();// 设置高亮数据for (SearchHit<User> hit : searchHits.getSearchHits()) {User content = hit.getContent();JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(content));Map<String, List<String>> highlightFields = hit.getHighlightFields();if (highlightFields.isEmpty()) {list.add(content);continue;}for (Map.Entry<String, List<String>> entry : highlightFields.entrySet()) {StringBuffer stringBuffer = new StringBuffer();for (int i = 0; i < entry.getValue().size(); i++) {if (i > 0) {stringBuffer.append(",");}stringBuffer.append(entry.getValue().get(i));}jsonObject.put(entry.getKey(), stringBuffer.toString());}content = JSONObject.parseObject(jsonObject.toJSONString(), User.class);list.add(content);}pageInfo.setList(list);return pageInfo;}
}