ElasticSearch版本升级,JestClient适配

邬飞捷
2023-12-01

背景:es原版本为6.6.2,现场项目要求升级至es7.17.1,项目使用jest实现es调用

问题点 1:创建mapping

升级前代码

public static boolean createIndexMapping(String indexName, String typeName, String source) throws Exception {

        PutMapping putMapping = new PutMapping.Builder(indexName, typeName, source).build();
        JestResult jr = jestClientImpl.execute(putMapping);

        logger.info(typeName + " mapping result : " + jr.getJsonString());
        return jr.isSucceeded();
    }

升级后代码

public static boolean createIndexMapping(String indexName, String typeName, String source) throws Exception {

        PutMapping putMapping = new PutMapping.Builder(indexName, typeName, source).setParameter("include_type_name", true).build();
        JestResult jr = jestClientImpl.execute(putMapping);

        logger.info(typeName + " mapping result : " + jr.getJsonString());
        return jr.isSucceeded();
    }

问题2:查询问题

升级前代码

SearchResult result = jestClient.execute(search);

searchResult.getTotal()

此处,由于es6系与7系返回json结构不一致,导致版本兼容问题,此处使用的jest的版本6.3.1,getTotal方法解析有误

源代码

public Long getTotal() {
        Long total = null;
        JsonElement obj = this.getPath(PATH_TO_TOTAL); //String[] PATH_TO_TOTAL = "hits/total".split("/")
        if (obj != null) {
            total = obj.getAsLong();
        }

        return total;
    }

解决思路,通过继承SearchResult,重写getTotal方法,解决报错

public class LocalSearchResult extends SearchResult {

    @Override
    public Long getTotal() {
        return this.getJsonObject().getAsJsonObject("hits").getAsJsonObject("total").get("value").getAsLong();
    }

    public AiccSearchResult(SearchResult searchResult) {
        super(searchResult);
    }

    public AiccSearchResult(Gson gson) {
        super(gson);
    }
}

经过验证,问题解决

转载请说明出处

 类似资料: