package com.elab.es.client;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.zxp.esclientrhl.repository.ElasticsearchTemplateImpl;
import org.zxp.esclientrhl.util.JsonUtils;

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

/**
 * 默认的ES模版处理器
 *
 * @author ： liukx
 * @time ： 2019/8/6 - 15:05
 */
public class DefaultElasticSearchTemplate<K, V> extends ElasticsearchTemplateImpl<K, V> {

    @Override
    public SearchResponse search(SearchRequest searchRequest) throws IOException {
        SearchResponse search = super.search(searchRequest);
        return search;
    }

    public <T> List<T> search(SearchRequest searchRequest, Class<T> clazz) throws IOException {
        SearchResponse searchResponse = super.search(searchRequest);
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();

        List<T> result = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            T t = JsonUtils.string2Obj(hit.getSourceAsString(), clazz);
            result.add(t);
        }
        return result;

    }


}
