ElasticSearch API实现返回指定的字段

source中包含多个字段,想在结果中返回用户指定的字段。下面的代码实现此功能。

SearchRequest request = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
searchSourceBuilder.from(0);
searchSourceBuilder.size(4);
String[] fields = {"hostIP","pathFile"};
FetchSourceContext sourceContext = new FetchSourceContext(fields);
//searchSourceBuilder.fetchSource(sourceContext);
boolQueryBuilder.should(new MatchQueryBuilder("hostIP", "10.184.133.213").operator(
        MatchQueryBuilder.Operator.AND).type(MatchQueryBuilder.Type.PHRASE));
searchSourceBuilder.query(boolQueryBuilder);
request.extraSource(searchSourceBuilder);
request.indices("ies_logcenter:pacihppackifeaaekhffmdafhiblbggm_20160706");
request.types("logCenter");
for(SearchHit hit:client.search(request).actionGet().getHits())
{
    System.out.println(hit.getSourceAsString());
}

result

{"category":"logAgent","hostIP":"10.184.133.213","hostName":"","lineNum":14677840880220008,"logContent":"2016-07-06 13:48:08,022 INFO  [http-bio-127.0.0.1-31803-exec-3][ROOT][logaccessservice.transfer.LogInfoQueue 148] log array size is 10","logTime":1467784088022,"pathFile":"/LogAccessService/logaccessservice-3176-0/log/root.log","tags":""}
{"category":"logAgent","hostIP":"10.184.133.213","hostName":"","lineNum":14677840880230009,"logContent":"2016-07-06 13:48:08,023 INFO  [http-bio-127.0.0.1-31803-exec-3][ROOT][logaccessservice.transfer.LogSendThreadPool 51] current thread num:0","logTime":1467784088023,"pathFile":"/LogAccessService/logaccessservice-3176-0/log/root.log","tags":""}
{"category":"logAgent","hostIP":"10.184.133.213","hostName":"","lineNum":14677840880230010,"logContent":"2016-07-06 13:48:08,023 INFO  [pool-5-thread-5793][ROOT][logaccessservice.transfer.JsonCvt 55] lineNum is 14676114189370001","logTime":1467784088023,"pathFile":"/LogAccessService/logaccessservice-3176-0/log/root.log","tags":""}
{"category":"logAgent","hostIP":"10.184.133.213","hostName":"","lineNum":14677840880240014,"logContent":"2016-07-06 13:48:08,024 INFO  [pool-5-thread-5793][ROOT][logaccessservice.transfer.JsonCvt 55] lineNum is 14676114197970005","logTime":1467784088024,"pathFile":"/LogAccessService/logaccessservice-3176-0/log/root.log","tags":""}

如果指定resouce字段

searchSourceBuilder.fetchSource(sourceContext);

结果就变为:

{"hostIP":"10.184.133.213","pathFile":"/LogAccessService/logaccessservice-3176-0/log/root.log"}
{"hostIP":"10.184.133.213","pathFile":"/LogAccessService/logaccessservice-3176-0/log/root.log"}
{"hostIP":"10.184.133.213","pathFile":"//LogAccessService/logaccessservice-3176-0/log/root.log"}
{"hostIP":"10.184.133.213","pathFile":"/LogAccessService/logaccessservice-3176-0/log/root.log"}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容