import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ScriptLanguage;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import com.dd.mall.common.api.CommonPage;
import com.dd.mall.common.constant.DeleteFlagEnum;
import com.dd.mall.demo.dto.ProductDetailOutVO;
import com.dd.mall.demo.utils.CommonPageBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Service
public class XiaoChenTestSearchServiceImpl {
@Resource
protected ElasticsearchClient syncElasticsearchClient;
@Resource
private XiaoChenTestService xiaoChenTestService;
public String getIndex() {
return xiaoChenTestService.getIndex();
}
public CommonPage<ProductDetailOutVO> searchProductByCategoryBrand() {
try {
List<String> categoryIds = Arrays.asList("3", "4", "5",
"6", "8", "9", "10", "12", "14", "16", "18",
"20", "22", "24", "26", "1660531830575726592");
List<Query> should = new ArrayList<>();
categoryIds.forEach(categoryId ->
should.add(TermQuery.of(m -> m.field("productCategoryId").value(categoryId))._toQuery()));
Long userLevelId = 1639106512590786560L;
SearchRequest searchRequest = new SearchRequest.Builder()
.index(getIndex())
.query(query -> query
.bool(bool -> bool.must(TermQuery.of(m -> m.field("brandId").value("1"))._toQuery())
.must(productCategoryIdShould -> productCategoryIdShould.bool(sb -> sb.should(should)))
.filter(TermQuery.of(m -> m.field("deleteFlag").value(DeleteFlagEnum.FLAG_0.getValue()))._toQuery())
.filter(TermQuery.of(m -> m.field("publishStatus").value(1))._toQuery())
)
).source(source -> source
.filter(f -> f
.includes("id", "name", "relationProductIdList")
.excludes("")
)
)
.sort(o -> o.field(f -> f.field("defaultSortValue").order(SortOrder.Desc)))
.scriptFields("priceNewTemp", field ->
field.script(script ->
script.inline(inline ->
inline.lang(ScriptLanguage.Painless)
.source("return (doc.containsKey('delearMinPriceMap." + userLevelId + "') ? (doc['delearMinPriceMap." + userLevelId + "'].value == null ? doc['price']" +
".value : doc['delearMinPriceMap." + userLevelId + "'].value) : doc['price'].value).doubleValue()")
)
))
.from(0)
.size(60)
.build();
SearchResponse<ProductDetailOutVO> searchResponse = syncElasticsearchClient.search(searchRequest, ProductDetailOutVO.class);
if (searchResponse != null && CollectionUtils.isNotEmpty(searchResponse.hits().hits())) {
List<ProductDetailOutVO> outVOList = new ArrayList<>();
List<Hit<ProductDetailOutVO>> hits = searchResponse.hits().hits();
hits.forEach(v -> {
Map<String, JsonData> fields = v.fields();
JsonData priceNewTemp = fields.get("priceNewTemp");
JSONArray array = JSONUtil.parseArray(priceNewTemp.toJson().toString());
List<Double> list = JSONUtil.toList(array, Double.class);
v.source().setPriceNewTemp(list.get(0));
outVOList.add(v.source());
});
return CommonPageBuilder.generate(searchResponse.hits().total() != null ? searchResponse.hits().total().value() : 0L,
outVOList, 60, 1);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
分页对象
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import java.util.ArrayList;
import java.util.List;
public class CommonPageBuilder {
public static <TDocument> CommonPage<TDocument> generateAsHits(SearchResponse<TDocument> searchResponse, Class<TDocument> tClass, Integer size, Integer page) {
CommonPage<TDocument> pageResult = new CommonPage<>();
HitsMetadata<TDocument> searchHits = searchResponse.hits();
List<Hit<TDocument>> hits = searchHits.hits();
List<TDocument> responseList = new ArrayList<>();
for (Hit<TDocument> hit : hits) {
responseList.add(hit.source());
}
pageResult.setList(responseList);
pageResult.setTotal(searchHits.total() != null ? searchHits.total().value() : 0);
pageResult.setPageNum(page);
pageResult.setPageSize(size);
pageResult.setTotalPage((int) Math.ceil((double) pageResult.getTotal() / size));
return pageResult;
}
public static <TDocument> CommonPage<TDocument> generate(long value, List<TDocument> documents, Integer size, Integer page) {
CommonPage<TDocument> pageResult = new CommonPage<>();
pageResult.setList(documents);
pageResult.setTotal(value);
pageResult.setPageNum(page);
pageResult.setPageSize(size);
pageResult.setTotalPage((int) Math.ceil((double) pageResult.getTotal() / size));
return pageResult;
}
}