0

我正在从我的 Java 代码运行各种 Elastic Search 查询。为了整合我的代码,我想在每个运行具有不同设置的 ElasticSearch 查询的条件循环之前初始化一个 SearchResponse 对象。这样,我可以执行一次代码来获取查询的总命中数。你会从代码中明白我的意思

@GET
@Path("/search")
public SearchResultsAndFacets search() {
    SearchResultsAndFacets srf = new SearchResultsAndFacets();
    RestHighLevelClient client = createHighLevelRestClient();
    // Build the base query that applies to all searches
    SearchSourceBuilder querySourceBuilder = buildQueryWrapper(colNames, sro.q, sro.f,
                facetsToUpdate, sro.u, sro.lc);
    SearchResponse searchresponse; // This line does not work. How can I initialize this object here (outside of the following conditional loops)?

    // Searches executed from the table view to populate a table of documents
    if (searchType.equals("table")) {
        List<SortParameters> sortParametersList = sortAdapter(sro.s);
        searchResponse = runTableQuery(client, querySourceBuilder, sortParameters, offset, limit);    
    }

    // Searches involving geo_point data to populate a leaflet map
    if (searchType.equals("contacts")) {
        RestHighLevelClient client = createHighLevelRestClient();

        ElasticSearchMapService esms = new ElasticSearchMapService();

        searchResponse = esms.runContactsMapQuery(querySourceBuilder, client, <some geographic coordinate parameters necessary for this search>);

        MapSearchResponse mapSearchResponse = esms.getLocationsFromSearchResponse(searchResponse);
        srf.mapSearchResponse = mapSearchResponse;
    }

// I would like to include these next few lines here at the end of the conditional loops.
// Currently they must be inside each if clause.
    srf.totalHits = searchResponse.getHits().getTotalHits().value;
    srf.elapsed = searchResponse.getTook().getMillis();
    srf.facetsData = getUpdatedFacetData(facetsToUpdate,
            searchResponse, sro.f);
    return srf;
}

Elastic 的 JAVA 高级 REST 客户端不允许像这样初始化 SearchResponse 对象。也不能这样做

SearchResponse searchResponse = new SearchResponse();

如果我们这样做会出现空指针错误......

SearchResponse searchResponse = new SearchResponse(null);

如何重写此代码,以便可以在条件循环之外获取 totalHits、elapsed 和 facetsData?

4

0 回答 0