import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
public class ESTest_Doc_Count {
public String suoyin_count (String args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//13、统计索引中字段的个数
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
//将传入的参数解析
String[] suoyin=args.split(",");
JSONObject result = new JSONObject();
String aggregations="";
String agecount="";
int value=0;
//按照传入的参数分别统计
for(int i=0;i<suoyin.length;i++){
String name=suoyin[i];
AggregationBuilder aggregationBuilder = AggregationBuilders.count(name).field(name);
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
JSONObject JSON = JSONObject.parseObject(response.toString());
if(JSON.getString("aggregations") != null & !JSON.getString("aggregations").trim().equals("")){
aggregations=JSON.getString("aggregations");
}
JSONObject JSON2 = JSONObject.parseObject(aggregations);
if(JSON2.getString("value_count#"+name) != null & !JSON2.getString("value_count#"+name).trim().equals("")){
agecount=JSON2.getString("value_count#"+name);
}
JSONObject JSON3 = JSONObject.parseObject(agecount);
if(JSON3.getInteger("value") != null ){
value=JSON3.getInteger("value");
}
result.put(name,value);
}
//关闭ES客户端
esClient.close();
return result.toString();
}
public static void main(String[] args) throws Exception {
ESTest_Doc_Count count = new ESTest_Doc_Count();
//查询一下索引中 age 和score 这两个字段分别有多少
String res= count.suoyin_count("age,score");
//输出结果
System.out.println("res:"+res);
}
}
?
|