pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
application.yml
data:
elasticsearch:
cluster-nodes: 10.0.0.219:9300
cluster-name: elasticsearch
POJO
package com.imooc.es.pojo;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
@Document(indexName = "foodie-items-ik",type = "doc",createIndex = false)
public class Items {
@Id
@Field(store = true,type = FieldType.Text,index = false)
private String itemId;
@Field(store = true,type = FieldType.Text,index = true)
private String itemName;
@Field(store = true,type = FieldType.Text,index = false)
private String imgUrl;
@Field(store = true,type = FieldType.Integer)
private Integer price;
@Field(store = true,type = FieldType.Integer)
private Integer sellCounts;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getSellCounts() {
return sellCounts;
}
public void setSellCounts(Integer sellCounts) {
this.sellCounts = sellCounts;
}
@Override
public String toString() {
return "Items{" +
"itemId=" + itemId +
", itemName='" + itemName + '\'' +
", imgUrl='" + imgUrl + '\'' +
", price=" + price +
", sellCounts=" + sellCounts +
'}';
}
}
Service
package com.imooc.service.impl;
import com.imooc.es.pojo.Items;
import com.imooc.es.pojo.Stu;
import com.imooc.service.ItemsESService;
import com.imooc.utils.PagedGridResult;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class ItemsESServiceImpl implements ItemsESService {
@Autowired
private ElasticsearchTemplate esTemplate;
@Override
public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize) {
String preTag = "<font color='red'>";
String postTag = "</font>";
Pageable pageable = PageRequest.of(page, pageSize);
String itemNameField = "itemName";
//排序条件
// SortBuilder sortBuilder = new FieldSortBuilder("money").order(SortOrder.ASC);
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery(itemNameField,keywords))
.withPageable(pageable)
// .withSort(sortBuilder)
.withHighlightFields(new HighlightBuilder.Field(itemNameField)
.preTags(preTag)
.postTags(postTag))
.build();
AggregatedPage<Items> pagedItmes = esTemplate.queryForPage(query, Items.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
SearchHits his = searchResponse.getHits();
List<Items> itemsHighList = new ArrayList<>();
for (SearchHit h : his) {
HighlightField highlightField = h.getHighlightFields().get(itemNameField);
String itemName = highlightField.getFragments()[0].toString();
String itemId = (String)h.getSourceAsMap().get("itemId");
String imgUrl = (String) h.getSourceAsMap().get("imgUrl");
Integer price = (Integer) h.getSourceAsMap().get("price");
Integer sellCounts = (Integer) h.getSourceAsMap().get("sellCounts");
Items items = new Items();
items.setItemName(itemName);
items.setItemId(itemId);
items.setImgUrl(imgUrl);
items.setPrice(price);
items.setSellCounts(sellCounts);
itemsHighList.add(items);
}
return new AggregatedPageImpl<>((List<T>)itemsHighList,pageable,searchResponse.getHits().totalHits);
}
});
PagedGridResult gridResult = new PagedGridResult();
gridResult.setRows(pagedItmes.getContent());
gridResult.setPage(page + 1);
gridResult.setTotal(pagedItmes.getTotalPages());
gridResult.setRecords(pagedItmes.getTotalElements());
return gridResult;
}
}
ESConfig
package com.imooc;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
public class ESConfig {
/**
* 解决netty引起的issue
*/
@PostConstruct
void init(){
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
}
Controller
package com.imooc.controller;
import com.imooc.service.ItemsESService;
import com.imooc.utils.JSONResult;
import com.imooc.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("items")
public class ItemsController {
@Autowired
private ItemsESService itemsESService;
@GetMapping("/search")
public JSONResult search(String keywords,String sort ,Integer page ,Integer pageSize){
if (StringUtils.isBlank(keywords)){
return JSONResult.errorMsg(null);
}
if (page == null){
page = 1;
}
if (pageSize == null){
pageSize = 20;
}
page --;
PagedGridResult gridResult = itemsESService.searchItems(keywords,sort,page,pageSize);
return JSONResult.ok(gridResult);
}
}
最后修改于 2020-04-21 10:15:20
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

