How java uses elasticsearch grouping for aggregate queries
This article mainly introduces java how to use elasticsearch grouping for aggregate query, the article is very detailed, has a certain reference value, interested friends must read it!
Java connects elasticsearch to aggregate queries and perform corresponding operations.
One: group summation of individual fields
1. Table structure picture:
According to the task id grouping, count the number of text titles under each task id.
1.SQL:select id, count (*) as sum from task group by taskid
Java ES connection utility class
Public class ESClientConnectionUtil {public static TransportClient client=null; public final static String HOST = "192.168.200.211"; / / Server deployment public final static Integer PORT = 9301; / / Port public static TransportClient getESClient () {System.setProperty ("es.set.netty.runtime.available.processors", "false") If (client = = null) {synchronized (ESClientConnectionUtil.class) {try {/ / set cluster name Settings settings = Settings.builder (). Put ("cluster.name", "es5"). Put ("client.transport.sniff", true). Build (); / / create client client = new PreBuiltTransportClient (settings) .addTransportAddress (new InetSocketTransportAddress (InetAddress.getByName (HOST), PORT);} catch (Exception ex) {ex.printStackTrace (); System.out.println (ex.getMessage ()) } return client;} public static TransportClient getESClientConnection () {if (client = = null) {System.setProperty ("es.set.netty.runtime.available.processors", "false"); try {/ / set cluster name Settings settings = Settings.builder (). Put ("cluster.name", "es5"). Put ("client.transport.sniff", true). Build (); / / create client client = new PreBuiltTransportClient (settings) .addTransportAddress (new InetSocketTransportAddress (InetAddress.getByName (HOST), PORT)) } catch (Exception ex) {ex.printStackTrace (); System.out.println (ex.getMessage ());}} return client;} / / determine whether the index exists public static boolean judgeIndex (String index) {client= getESClientConnection (); IndicesAdminClient adminClient; / / query whether the index exists adminClient= client.admin (). Indices (); IndicesExistsRequest request = new IndicesExistsRequest (index); IndicesExistsResponse responses = adminClient.exists (request). ActionGet (); if (responses.isExists ()) {return true;} return false;}}
Java ES statement (group summation based on a single column)
/ summing according to task id grouping SearchRequestBuilder sbuilder = client.prepareSearch ("hottopic"). SetTypes ("hot"); / / grouping statistics according to taskid, the column is named sum TermsAggregationBuilder termsBuilder = AggregationBuilders.terms ("sum"). Field ("taskid"); sbuilder.addAggregation (termsBuilder); SearchResponse responses= sbuilder.execute (). ActionGet (); / / get the data set of this grouping Terms terms = responses.getAggregations (). Get ("sum"); List lists = new ArrayList () For (int iTuno Bandi)