Jest实现ElasticSearch返回指定的字段

在很多使用ElasticSearch的时候都会遇到查找出来的文档过大的情况,那么能不能像MySql一样只返回我们需要的字段呢?答案显示是可以的,那么下面介绍一下如何让ES只返回指定的字段。

 

一、源码

@Override
    public JsonObject getEsTestInfo(EsRequestBean esRequestBean){
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        try{
            if (!esRequestBean.getStartTime().isEmpty()){
                queryBuilder.must(QueryBuilders.rangeQuery("startTime").gte(esRequestBean.getStartTime()));
            }
            if (!esRequestBean.getEndTime().isEmpty()){
                queryBuilder.must(QueryBuilders.rangeQuery("endTime").lte(esRequestBean.getEndTime()));
            }
            if (!esRequestBean.getTestCode().isEmpty()){
                queryBuilder.must(QueryBuilders.matchQuery("testCode", esRequestBean.getTestCode()));
            }
            searchSourceBuilder.query(queryBuilder).fetchSource("scNumber", null);
            Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).addType(typeName).build();
            JestResult jestResult = jestClient.execute(search);
            return jestResult.getJsonObject();
        }catch (IOException e){
            logger.error("Get info IOException:" + e);
            return null;
        }catch (Exception e){
            logger.error("Get info Exception:" + e);
            return null;
        }
    }

代码基于另一篇博文:SpringBoot下使用Jest实现对ElasticSearch的多条件查询 的基础上进行改造,这样我们就可以指定文档内容只返回scNumber这个字段的信息了,那后面的null又是什么意思呢?下面进行一下解释。

 

二、fetchSource方法说明

由代码可知,fetchSource是SearchSourceBuilder中的一个方法,点击进去查看源码。

/**
     * Indicate that _source should be returned with every hit, with an
     * "include" and/or "exclude" set which can include simple wildcard
     * elements.
     *
     * @param include
     *            An optional include (optionally wildcarded) pattern to filter
     *            the returned _source
     * @param exclude
     *            An optional exclude (optionally wildcarded) pattern to filter
     *            the returned _source
     */
    public SearchSourceBuilder fetchSource(@Nullable String include, @Nullable String exclude) {
        return fetchSource(include == null ? Strings.EMPTY_ARRAY : new String[] { include }, exclude == null ? Strings.EMPTY_ARRAY
                : new String[] { exclude });
    }

    /**
     * Indicate that _source should be returned with every hit, with an
     * "include" and/or "exclude" set which can include simple wildcard
     * elements.
     *
     * @param includes
     *            An optional list of include (optionally wildcarded) pattern to
     *            filter the returned _source
     * @param excludes
     *            An optional list of exclude (optionally wildcarded) pattern to
     *            filter the returned _source
     */
    public SearchSourceBuilder fetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
        FetchSourceContext fetchSourceContext = this.fetchSourceContext != null ? this.fetchSourceContext
            : FetchSourceContext.FETCH_SOURCE;
        this.fetchSourceContext = new FetchSourceContext(fetchSourceContext.fetchSource(), includes, excludes);
        return this;
    }

原本是有五种,这里挑选最常用的两种进行说明。

第一个自然就是我们刚刚演示所用到的方法:fetchSource(@Nullable String include, @Nullable String exclude)

进行了Nullable的注解,意味着可以为空,那么为什么可以为空呢?查看上方注释之后得悉,fetchSource(@Nullable String include, @Nullable String exclude)中的include表示返回结果里要包含哪个字段,exclude是不包含哪个字段。所以fetchSource("scNumber", null)就是只返回_source中的scNumber字段,没有需要剔除的字段。

执行结果:

{
    "hits": [
        {
            "scNumber": "test111"
        },
        {
            "scNumber": "test112"
        }
    ]
}

这里是已经经过解析的结果,如何将结果直接放置到指定实体见另一篇博文。同理的指定exclude便是不会包含该字段。那么两者内容一致怎么办?感兴趣的可以自己试一试,结果也确实在预期之内。

 

第二个:fetchSource(@Nullable String[] includes, @Nullable String[] excludes),自然也就是返回多个字段的信息,这里就不再赘述了。

 

你可能感兴趣的:(ElasticSearch,SpringBoot,Java)