spring cloud 集成elasticsearch 实现findByIds查询

我们使用elasticsearch常使用它的分词查询,但是因为业务需要也需要使用多id查询,elasticsearch提供了MultiGetRequest实现多ids,多索引查询:

/**
     * 根据多个索引查询
     */
    public  List findByIds(List keys, Class clazz) {
        RestHighLevelClient client=this.restHighLevelClient();
        try {
            if(null == keys || keys.size() == 0){
                return  null;
            }
            // 通过MultiGetRequest.Item对象设置查询参数
            MultiGetRequest request = new MultiGetRequest();
            String[] ids = new String[keys.size()];
            for(int i = 0;i< keys.size();i++){
                ids[i] = keys.get(i);
                request.add( "索引名", keys.get(i));
            }
            List  productList = Lists.newArrayList();
            MultiGetResponse response = client.mget(request, RequestOptions.DEFAULT);
            log.info("ES-findById:id[{}],result:{}", JSON.toJSONString(keys),response.getResponses());
            if(!response.isFragment()){
                for(MultiGetItemResponse multiGetItemResponse :response.getResponses()){
                    GetResponse firstGet = multiGetItemResponse.getResponse();
                    if (firstGet.isExists()) {
                        String value =firstGet.getSourceAsString();
                        productList.add(JSONObject.parseObject(value,clazz)) ;
                    }
                }
            }
            return productList;
        } catch (Exception e) {
            throw new BizException(" findByIndexIds 搜索引擎异常:"+e.getMessage());
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

你可能感兴趣的:(elasticsearch,SpringCloud,elasticsearch,spring,cloud,搜索引擎)