Java API操作ES8.x-查询


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 {


    /**
     * 将查询结果变成 CommonPage  自己项目中的
     *
     * @param searchResponse es查询返回结果
     * @param tClass         实体类
     * @param size           大小
     * @param page           当前页
     * @param <TDocument>    实体泛型
     * @return CommonPage 结果
     */
    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;
    }
}
### 使用 Docker 搭建 Elasticsearch 8.x 版本 要使用 Docker 部署 Elasticsearch 8.x,可以按照以下方法操作: #### 准备工作 确保已安装并运行 Docker 和 Docker Compose。可以通过命令 `docker --version` 和 `docker-compose --version` 来验证。 #### 创建必要的目录和文件 根据引用[^2]的内容,在本地创建所需的目录结构以及配置文件: ```bash mkdir -p /path/to/elasticsearch/{config,data,plugins} touch /path/to/elasticsearch/config/elasticsearch.yml ``` 编辑 `elasticsearch.yml` 文件以满足需求。例如,允许远程访问时需设置如下参数: ```yaml http.host: 0.0.0.0 network.host: 0.0.0.0 cluster.initial_master_nodes: ["node-1"] xpack.security.enabled: false ``` 注意:上述配置中禁用了安全功能 (`xpack.security.enabled`),仅适用于开发环境测试用途;生产环境中应启用安全性选项[^3]。 #### 启动容器 编写一个简单的 `docker-compose.yml` 文件来定义服务: ```yaml version: '3' services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:8.9.0 container_name: elasticsearch environment: - discovery.type=single-node - ES_JAVA_OPTS=-Xms512m -Xmx512m volumes: - /path/to/elasticsearch/data:/usr/share/elasticsearch/data - /path/to/elasticsearch/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml - /path/to/elasticsearch/plugins:/usr/share/elasticsearch/plugins ports: - "9200:9200" - "9300:9300" restart: always ``` 执行启动命令: ```bash docker-compose up -d ``` 此时应该能够通过浏览器或者 curl 命令访问默认端口上的 API 接口地址(如 http://localhost:9200),确认实例正常运作。 关于审计日志记录方面的要求,请参照官方文档说明完成相应部分的自定义调整[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值