package com.goomood.es.service;

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.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author pawn
 * @version 1.0
 * @description: 搜索service
 * @date 2024/11/19 16:03
 */
@Service
public class SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 在 ES 中通过关键字同时搜索文件内容和名称
     *
     * @param keyword 关键字
     * @return 搜索结果
     * @throws IOException
     */
    public List<Map<String, Object>> searchByKeyword(String keyword) throws IOException {
        // 构造查询请求
        SearchRequest searchRequest = new SearchRequest("file_content_index");

        // 使用 bool 查询，同时匹配文件内容和名称
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.boolQuery()
                // 文件内容字段
                .should(QueryBuilders.matchQuery("attachment.content", keyword)).boost(2.0f)
                // 文件名称字段
                .should(QueryBuilders.matchQuery("fileName", keyword))
        );
        sourceBuilder.fetchSource(new String[]{
                "fileName", "fileUrl", "fileType", "belongType", "belongId", "belongName", "attachment.content"
        }, null);

        // 设置分页，size 控制每次返回的数据条数
        sourceBuilder.size(5);

        searchRequest.source(sourceBuilder);

        // 执行搜索
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 处理搜索结果
        List<Map<String, Object>> results = new ArrayList<>();
        response.getHits().forEach(hit -> results.add(hit.getSourceAsMap()));
        return results;
    }
}
