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"}