ES 商城搜索简单搜索示例

mapping结构

{
	"settings": {
		"analysis": {
			"normalizer": {
				"lowercase_normalizer": {
					"type": "custom",
					"char_filter": [],
					"filter": [
						"lowercase"
					]
				}
			}
		}
	},
	"mappings": {
		"dynamic": false,
		"properties": {
			"id": {
				"type": "integer"
			},
			"spuNo": {
				"type": "keyword"
			},
			"corpCode": {
				"type": "keyword"
			},
			"platformCatalogCode": {
				"type": "keyword"
			},
			"attributeTemplate": {
				"type": "nested",
				"properties": {
					"attributeCode": {
						"type": "keyword"
					},
					"attributeName": {
						"type": "text",
						"analyzer": "ik_max_word"
					},
					"attributeValue": {
						"type": "text",
						"fields": {
							"keyword": {
								"type": "keyword"
							}
						}
					},
					"allAttributeValue": {
						"type": "text",
						"fields": {
							"keyword": {
								"type": "keyword"
							}
						}
					},
					"source": {
						"type": "integer",
						"ignore_malformed": true
					},
					"inputType": {
						"type": "integer",
						"ignore_malformed": true
					},
					"isRequired": {
						"type": "integer",
						"ignore_malformed": true
					}
				}
			},
			"platformAttributeVersion": {
				"type": "keyword"
			},
			"standardTemplate": {
				"type": "nested",
				"properties": {
					"standardCode": {
						"type": "keyword"
					},
					"standardName": {
						"type": "text",
						"analyzer": "ik_max_word"
					},
					"standardValue": {
						"type": "text",
						"fields": {
							"keyword": {
								"type": "keyword"
							}
						}
					},
					"allStandardValue": {
						"type": "text",
						"fields": {
							"keyword": {
								"type": "keyword"
							}
						}
					},
					"source": {
						"type": "integer",
						"ignore_malformed": true
					},
					"inputType": {
						"type": "integer",
						"ignore_malformed": true
					},
					"sort": {
						"type": "integer",
						"ignore_malformed": true
					}
				}
			},
			"platformStandardVersion": {
				"type": "keyword"
			},
			"goodsName": {
				"type": "text",
				"analyzer": "ik_max_word",
				"fields": {
					"keyword": {
						"type": "keyword",
						"normalizer": "lowercase_normalizer",
						"ignore_above": 256
					}
				}
			},
			"goodsNo": {
				"type": "text",
				"analyzer": "ik_max_word",
				"fields": {
					"keyword": {
						"type": "keyword",
						"normalizer": "lowercase_normalizer",
						"ignore_above": 256
					}
				}
			},
			"goodsDesc": {
				"type": "text"
			},
			"spuPic": {
				"type": "text",
				"fields": {
					"keyword": {
						"type": "keyword"
					}
				}
			},
			"keywords": {
				"type": "keyword"
			},
			"remark": {
				"type": "text"
			},
			"unitPrice": {
				"type": "double",
				"ignore_malformed": true
			},
			"unit": {
				"type": "keyword"
			},
			"saleUnit": {
				"type": "keyword"
			},
			"currency": {
				"type": "keyword"
			},
			"source": {
				"type": "integer",
				"ignore_malformed": true
			},
			"goodsDimension": {
				"type": "integer",
				"ignore_malformed": true
			},
			"deliveryDate": {
				"type": "integer",
				"ignore_malformed": true
			},
			"status": {
				"type": "integer",
				"ignore_malformed": true
			},
			"createBy": {
				"type": "integer",
				"ignore_malformed": true
			},
			"modifyBy": {
				"type": "integer",
				"ignore_malformed": true
			},
			"createTime": {
				"type": "date",
				"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis",
				"ignore_malformed": true
			},
			"modifyTime": {
				"type": "date",
				"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis",
				"ignore_malformed": true
			},
			"deleted": {
				"type": "integer",
				"ignore_malformed": true
			}
		}
	}
}
// 构建查询条件
private BoolQueryBuilder queryBuilder(String name, List<MallSearchGoodsStandardParam> standardInfo, List<MallSearchGoodsAttributeParam> attributeInfo, List<String> lastPlatformCatalogCode, List<String> isSampleSpuList, String corpCode) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 先过滤一下
        boolQuery.filter(QueryBuilders.termQuery("status", 1))
                .filter(QueryBuilders.termQuery("deleted", 0))
                .filter(QueryBuilders.termQuery("goodsDimension", 0))
                .filter(QueryBuilders.existsQuery("goodsName"));
        if (CollectionUtils.isNotEmpty(lastPlatformCatalogCode)) {
            boolQuery.filter(QueryBuilders.termsQuery("platformCatalogCode", lastPlatformCatalogCode));
        }
        if(StringUtils.isNotBlank(corpCode)){
            boolQuery.filter(QueryBuilders.termQuery("corpCode", corpCode));
        }
        if (StringUtils.isNotBlank(name)) {
            /*// 搜索关键字有值 查询编码和名称 如果编码查的是完整的就要term精准匹配goodsNo.keyword和goodsName.keyword但是也有可能是编码的部分 但不分词要term一下 他们之间的关系是or的关系,搜索名称要分词 顺序可能打乱的 所以match的时候operator是and
            boolQuery.must(QueryBuilders.boolQuery()
                    .should(QueryBuilders.termQuery("goodsNo.keyword", name))
                    .should(QueryBuilders.termQuery("goodsName.keyword", name))
                    .should(QueryBuilders.termQuery("goodsNo", name))
                    .should(QueryBuilders.matchQuery("goodsName", name).operator(Operator.AND)));*/
            // BEST_FIELDS 查询结果使用最佳字段的score作为最终评分,MOST_FIELDS 查询结果符合条件的字段的score分数加起来,CROSS_FIELDS 跨字段匹配(假如查询hello world,A字段数据包含hello,B字段数据包含world,最佳匹配很可能就是这个文档)
            // Operator.AND 假如搜索高级程序员,分词分为高级和程序员 在一个字段中必须既有高级又有程序员才可以 顺序可以是反的程序员高级 也能搜到
            MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery(name, "goodsNo", "goodsNo.keyword", "goodsName", "goodsName.keyword");
            multiMatchQuery.type(MultiMatchQueryBuilder.Type.MOST_FIELDS);
            multiMatchQuery.operator(Operator.AND);
            boolQuery.must(multiMatchQuery);
        }
        // 查试料商品
        if (CollectionUtils.isNotEmpty(isSampleSpuList)) {
            boolQuery.must(QueryBuilders.termsQuery("spuNo", isSampleSpuList));
        }
        // 按照查规格查询 构建索引结构时 规格和属性都是nested类型
        if (CollectionUtils.isNotEmpty(standardInfo)) {
            standardInfo.forEach(l -> {
                BoolQueryBuilder nestQueryBuilder = QueryBuilders.boolQuery();
                if (StringUtils.isNotBlank(l.getStandardCode())) {
                    nestQueryBuilder.must(QueryBuilders.termQuery("standardTemplate.standardCode", l.getStandardCode()));
                }
                if (CollectionUtils.isNotEmpty(l.getStandardValue())) {
                    l.getStandardValue().forEach(value -> {
                        nestQueryBuilder.must(QueryBuilders.termQuery("standardTemplate.standardValue.keyword", value));
                    });
                }
                boolQuery.must(QueryBuilders.nestedQuery("standardTemplate", nestQueryBuilder, ScoreMode.None));
            });
        }
        if (CollectionUtils.isNotEmpty(attributeInfo)) {
            attributeInfo.forEach(l -> {
                BoolQueryBuilder nestQueryBuilder = QueryBuilders.boolQuery();
                if (StringUtils.isNotBlank(l.getAttributeCode())) {
                    nestQueryBuilder.must(QueryBuilders.termQuery("attributeTemplate.attributeCode", l.getAttributeCode()));
                }
                if (CollectionUtils.isNotEmpty(l.getAttributeValue())) {
                    l.getAttributeValue().forEach(value -> {
                        nestQueryBuilder.must(QueryBuilders.termQuery("attributeTemplate.attributeValue.keyword", value));
                    });
                }
                boolQuery.must(QueryBuilders.nestedQuery("attributeTemplate", nestQueryBuilder, ScoreMode.None));
            });
        }
        return boolQuery;
    }

 query简单使用可以看下这两个




query简单使用可以看下这两个Elasticsearch QueryBuilder简单查询实现解析 - java基础 - 谷谷点程序

https://www.cnblogs.com/atao-BigData/p/16845431.html

封装的一些方法代码

package com.smartchain.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.smartchain.core.constant.Constants;
import com.smartchain.core.exception.BusinessException;
import com.smartchain.dto.goods.AttributeTemplateInfoDTO;
import com.smartchain.dto.goods.ElasticSearchGoodsVO;
import com.smartchain.dto.goods.StandardTemplateInfoDTO;
import com.smartchain.goods.domain.BasCorpGoodsSkuDO;
import com.smartchain.goods.domain.BasCorpGoodsSpuDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author cyc
 * @date 2023-6-20 16:11:50
 */
@Slf4j
@Service
public class ElasticSearchGoodsService {
    private static final String GOODS_INDEX = "v6_spu";

    @Resource
    private RestHighLevelClient client;

    /**
     * 自定义解析器 keyword类型 忽略大小写
     */
    private final String setting ="{\n" +
            "\t\t\"analysis\": {\n" +
            "\t\t\t\"normalizer\": {\n" +
            "\t\t\t\t\"lowercase_normalizer\": {\n" +
            "\t\t\t\t\t\"type\": \"custom\",\n" +
            "\t\t\t\t\t\"char_filter\": [],\n" +
            "\t\t\t\t\t\"filter\": [\n" +
            "\t\t\t\t\t\t\"lowercase\"\n" +
            "\t\t\t\t\t]\n" +
            "\t\t\t\t}\n" +
            "\t\t\t}\n" +
            "\t\t}\n" +
            "\t}";

    private final String mapping = "{\n" +
            "\t\t\"dynamic\": false,\n" +
            "\t\t\"properties\": {\n" +
            "\t\t\t\"id\": {\n" +
            "\t\t\t\t\"type\": \"integer\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"spuNo\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"corpCode\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"platformCatalogCode\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"attributeTemplate\": {\n" +
            "\t\t\t\t\"type\": \"nested\",\n" +
            "\t\t\t\t\"properties\": {\n" +
            "\t\t\t\t\t\"attributeCode\": {\n" +
            "\t\t\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"attributeName\": {\n" +
            "\t\t\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\t\t\"analyzer\": \"ik_max_word\"\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"attributeValue\": {\n" +
            "\t\t\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\t\t\"fields\": {\n" +
            "\t\t\t\t\t\t\t\"keyword\": {\n" +
            "\t\t\t\t\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"allAttributeValue\": {\n" +
            "\t\t\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\t\t\"fields\": {\n" +
            "\t\t\t\t\t\t\t\"keyword\": {\n" +
            "\t\t\t\t\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"source\": {\n" +
            "\t\t\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"inputType\": {\n" +
            "\t\t\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"isRequired\": {\n" +
            "\t\t\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t\t\t}\n" +
            "\t\t\t\t}\n" +
            "\t\t\t},\n" +
            "\t\t\t\"platformAttributeVersion\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"standardTemplate\": {\n" +
            "\t\t\t\t\"type\": \"nested\",\n" +
            "\t\t\t\t\"properties\": {\n" +
            "\t\t\t\t\t\"standardCode\": {\n" +
            "\t\t\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"standardName\": {\n" +
            "\t\t\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\t\t\"analyzer\": \"ik_max_word\"\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"standardValue\": {\n" +
            "\t\t\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\t\t\"fields\": {\n" +
            "\t\t\t\t\t\t\t\"keyword\": {\n" +
            "\t\t\t\t\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"allStandardValue\": {\n" +
            "\t\t\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\t\t\"fields\": {\n" +
            "\t\t\t\t\t\t\t\"keyword\": {\n" +
            "\t\t\t\t\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"source\": {\n" +
            "\t\t\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"inputType\": {\n" +
            "\t\t\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t\t\t},\n" +
            "\t\t\t\t\t\"sort\": {\n" +
            "\t\t\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t\t\t}\n" +
            "\t\t\t\t}\n" +
            "\t\t\t},\n" +
            "\t\t\t\"platformStandardVersion\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"goodsName\": {\n" +
            "\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\"analyzer\": \"ik_max_word\",\n" +
            "\t\t\t\t\"fields\": {\n" +
            "\t\t\t\t\t\"keyword\": {\n" +
            "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
            "\t\t\t\t\t\t\"normalizer\": \"lowercase_normalizer\",\n" +
            "\t\t\t\t\t\t\"ignore_above\": 256\n" +
            "\t\t\t\t\t}\n" +
            "\t\t\t\t}\n" +
            "\t\t\t},\n" +
            "\t\t\t\"goodsNo\": {\n" +
            "\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\"analyzer\": \"ik_max_word\",\n" +
            "\t\t\t\t\"fields\": {\n" +
            "\t\t\t\t\t\"keyword\": {\n" +
            "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
            "\t\t\t\t\t\t\"normalizer\": \"lowercase_normalizer\",\n" +
            "\t\t\t\t\t\t\"ignore_above\": 256\n" +
            "\t\t\t\t\t}\n" +
            "\t\t\t\t}\n" +
            "\t\t\t},\n" +
            "\t\t\t\"goodsDesc\": {\n" +
            "\t\t\t\t\"type\": \"text\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"spuPic\": {\n" +
            "\t\t\t\t\"type\": \"text\",\n" +
            "\t\t\t\t\"fields\": {\n" +
            "\t\t\t\t\t\"keyword\": {\n" +
            "\t\t\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t\t\t}\n" +
            "\t\t\t\t}\n" +
            "\t\t\t},\n" +
            "\t\t\t\"keywords\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"remark\": {\n" +
            "\t\t\t\t\"type\": \"text\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"unitPrice\": {\n" +
            "\t\t\t\t\"type\": \"double\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"unit\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"saleUnit\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"currency\": {\n" +
            "\t\t\t\t\"type\": \"keyword\"\n" +
            "\t\t\t},\n" +
            "\t\t\t\"source\": {\n" +
            "\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"goodsDimension\": {\n" +
            "\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"deliveryDate\": {\n" +
            "\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"status\": {\n" +
            "\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"createBy\": {\n" +
            "\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"modifyBy\": {\n" +
            "\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"createTime\": {\n" +
            "\t\t\t\t\"type\": \"date\",\n" +
            "\t\t\t\t\"format\": \"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"modifyTime\": {\n" +
            "\t\t\t\t\"type\": \"date\",\n" +
            "\t\t\t\t\"format\": \"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t},\n" +
            "\t\t\t\"deleted\": {\n" +
            "\t\t\t\t\"type\": \"integer\",\n" +
            "\t\t\t\t\"ignore_malformed\": true\n" +
            "\t\t\t}\n" +
            "\t\t}\n" +
            "\t}";

    public Boolean createIndexMapping() {
        CreateIndexRequest request = new CreateIndexRequest(GOODS_INDEX);
        request.settings(setting, XContentType.JSON);
        request.mapping(mapping, XContentType.JSON);
        try {
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            log.info("创建索引:{}结果:{}", GOODS_INDEX, createIndexResponse.isAcknowledged());
            return createIndexResponse.isAcknowledged();
        } catch (Exception e) {
            log.error("create index elasticsearch error: ", e);
            throw new BusinessException("创建索引失败");
        }
    }

    public PageInfo<ElasticSearchGoodsVO> getSearchRequestAndSearch(Integer page, Integer limit, BoolQueryBuilder boolQuery) {
        PageInfo<ElasticSearchGoodsVO> pageInfo = new PageInfo<>();
        List<ElasticSearchGoodsVO> vo = new ArrayList<>();
        SearchRequest searchRequest = new SearchRequest(GOODS_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQuery);
        searchSourceBuilder.from((page - 1) * limit);
        searchSourceBuilder.size(limit);
        searchRequest.source(searchSourceBuilder);
        log.info("es请求开始");
        log.info("es请求参数:{}", searchRequest.toString());
        SearchResponse res;
        try {
            res = client.search(searchRequest, RequestOptions.DEFAULT);
            log.info("es请求响应:{},耗时:{}", res, res.getTook());
        } catch (IOException e) {
            log.error("search exist elasticsearch error: ", e);
            throw new BusinessException("系统异常,请重试");
        }
        if (!ObjectUtils.isEmpty(res.getHits()) && !ObjectUtils.isEmpty(res.getHits().getHits())) {
            SearchHit[] hits = res.getHits().getHits();
            for (SearchHit hit : hits) {
                vo.add(JSON.parseObject(hit.getSourceAsString(), ElasticSearchGoodsVO.class));
            }
        }
        log.info("es请求结束,最终封装list:{}", JSON.toJSONString(vo));
        TotalHits totalHits = res.getHits().getTotalHits();
        pageInfo.setList(vo);
        pageInfo.setTotal(!ObjectUtils.isEmpty(totalHits) ? totalHits.value : 0L);
        return pageInfo;
    }

    public IndexRequest getAddRequest(BasCorpGoodsSpuDO spuDO, List<BasCorpGoodsSkuDO> skuDOList) {
        if (spuDO.getDeleted() != 0) {
            return null;
        }
        ElasticSearchGoodsVO spu = new ElasticSearchGoodsVO();
        BeanUtils.copyProperties(spuDO, spu);
        spu.setAttributeTemplate(JSON.parseArray(spuDO.getAttributeTemplate(), AttributeTemplateInfoDTO.class));
        spu.setStandardTemplate(JSON.parseArray(spuDO.getStandardTemplate(), StandardTemplateInfoDTO.class));
        spu.setSpuPic(JSON.parseArray(spuDO.getSpuPic(), String.class));
        spu.setGoodsDesc(JSON.parseArray(spuDO.getGoodsDesc(), String.class));
        IndexRequest request = new IndexRequest(GOODS_INDEX);
        request.id(spu.getId().toString());
        request.source(JSON.toJSONString(spu), XContentType.JSON);
        return request;
    }

    public Integer bulkDel(List<Long> goodsIdList) {
        BulkRequest request = new BulkRequest();
        for (Long id : goodsIdList) {
            DeleteRequest deleteRequest = new DeleteRequest(GOODS_INDEX, id.toString());
            request.add(deleteRequest);
        }
        if (ObjectUtils.isEmpty(request)) {
            return Constants.NO;
        }
        List<String> ids = new ArrayList<>();
        try {
            log.info("es批量删除,操作请求:{}", request.requests());
            BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
            BulkItemResponse[] items = bulk.getItems();
            if (Boolean.TRUE.equals(bulk.hasFailures())) {
                log.error("批量新增有错误:{}", bulk.buildFailureMessage());
            }
            for (BulkItemResponse item : items) {
                ids.add(item.getId());
            }
            log.info("es批量删除,删除成功,商品spu id:{},成功条数:{},耗时:{}", JSON.toJSONString(ids), items.length, bulk.getTook().getMillis());
        } catch (IOException e) {
            log.error("delete elasticsearch error: ", e);
            throw new BusinessException("系统异常,请重试");
        }
        return ids.size();
    }

    public Integer bulkAddOrUpdate(List<IndexRequest> requests) {
        if (ObjectUtils.isEmpty(requests)) {
            return Constants.NO;
        }
        BulkRequest request = new BulkRequest();
        for (IndexRequest indexRequest : requests) {
            request.add(indexRequest);
        }
        List<String> ids = new ArrayList<>();
        try {
            log.info("es批量新增/更新,操作请求:{}", request.requests());
            BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
            BulkItemResponse[] items = bulk.getItems();
            if (Boolean.TRUE.equals(bulk.hasFailures())) {
                log.error("批量新增/更新有错误:{}", bulk.buildFailureMessage());
            }
            for (BulkItemResponse item : items) {
                ids.add(item.getId());
            }
            log.info("es批量新增/更新,操作成功,商品spu id:{},成功条数:{},耗时:{}", JSON.toJSONString(ids), items.length, bulk.getTook().getMillis());
        } catch (IOException e) {
            log.error("create elasticsearch error: ", e);
            throw new BusinessException("系统异常,请重试");
        }
        return ids.size();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值