Elasticsearch Java API-Aggregate query

Source: Internet
Author: User
Tags elastic search
Take player information as an example, the player index player type contains 5 fields, name, age, Salary, team, field position. The mapping of Index is:
"Mappings": {"quote": {"
	properties": {
		"adj_close": {"
				type": "Long"
			},
			"open": {
				" Type ': ' Long '
			},
			' symbol ': {
				' index ': ' not_analyzed ',
				' type ': ' String '
			},
			' volume ': {
				' type ': ' Long '
			},
			' high ': {
				' type ': ' Long '
			},
			' low ': {
				' type ': ' Long '
			},
			' Date ': {
				' format ': ' strict_date_optional_time| | Epoch_millis ",
				Type": "Date"
			},
			"Close": {
				"type": "Long"
			}
		},
		"_all": {
			' Enabled ': false}}
}

All data in the index: Td>wigins
name age salary team position
James 3000 cav SF
Irving 2000 CAV pg
Curry 1000 war PG
Thompson @ num war sg
Green num war pf
Garnett $ 1000 /td> Tim pf
towns $ Tim c
Lavin tim sg
+ Tim SF
First, initialize the builder:
Searchrequestbuilder Sbuilder = Client.preparesearch ("Player"). Settypes ("Player");
The following example illustrates the implementation methods of various aggregation operations, because in the ES API, the aggregation operation on many fields needs to use the subaggregation, the beginner may not find the method (the data on the net is less, the author has been tossing the problem for two days, finally the source code is thoroughly understood T_ T), the implementation of multiple-field aggregation is specifically described. In addition, the sort that is aggregated is also described separately. 1. Group By/countFor example, to calculate the number of players per team, if you use SQL statements, you should say the following:
Select Team, COUNT (*) as Player_count from player group by team;
Java API for ES:
Termsbuilder teamagg= aggregationbuilders.terms ("Player_count"). Field ("Team");
Sbuilder.addaggregation (Teamagg);
SearchResponse response = Sbuilder.execute (). Actionget ();
2.group by multiple fieldFor example, to calculate the number of players per team location, if you use SQL statements, you should say the following:
Select Team, Position, COUNT (*) as Pos_count from player group by team, position;
Java API for ES:
Termsbuilder teamagg= aggregationbuilders.terms ("Player_count"). Field ("Team");
Termsbuilder posagg= aggregationbuilders.terms ("Pos_count"). Field ("position");
Sbuilder.addaggregation (Teamagg.subaggregation (Posagg));
SearchResponse response = Sbuilder.execute (). Actionget ();
3.max/min/sum/avgFor example, to calculate the age of the maximum/minimum/total/average player age for each team, if using SQL statements, it should be expressed as follows:
Select Team, Max (age) as max_age from player group by team;
Java API for ES:
Termsbuilder teamagg= aggregationbuilders.terms ("Player_count"). Field ("Team");
Maxbuilder ageagg= Aggregationbuilders.max ("Max_age"). Field ("Age");
Sbuilder.addaggregation (Teamagg.subaggregation (Ageagg));
SearchResponse response = Sbuilder.execute (). Actionget ();
4. Seek max/min/sum/avg for multiple fieldFor example, to calculate the average age of each team player, while also calculating the total annual salary, if the use of SQL statements, should be expressed as follows:
Select Team, AVG (age) as Avg_age, sum (salary) as total_salary from player group by team;
Java API for ES:
Termsbuilder teamagg= aggregationbuilders.terms ("team");
Avgbuilder ageagg= aggregationbuilders.avg ("Avg_age"). Field ("Age");
Sumbuilder salaryagg= aggregationbuilders.avg ("Total_salary"). Field ("Salary");
Sbuilder.addaggregation (Teamagg.subaggregation (Ageagg). Subaggregation (Salaryagg));
SearchResponse response = Sbuilder.execute (). Actionget ();
5. Ordering of aggregation results after polymerizationFor example, to calculate the total annual salary of each team, and according to the total annual salary in reverse order, if the use of SQL statements, should be expressed as follows:
Select Team, SUM (salary) as total_salary from the player group by total_salary Desc;
Java API for ES:
Termsbuilder teamagg= aggregationbuilders.terms ("Team"). Order (Order.aggregation ("Total_salary", false);
Sumbuilder salaryagg= aggregationbuilders.avg ("Total_salary"). Field ("Salary");
Sbuilder.addaggregation (Teamagg.subaggregation (Salaryagg));
SearchResponse response = Sbuilder.execute (). Actionget ();

Of particular note is that the sort is performed at Termaggregation, the first argument of the Order.aggregation function is the name of aggregation, the second argument is Boolean, true is positive, and false indicates reverse. 6.Aggregation Result Bar number problemBy default, search executes only 10 aggregate results, and if you want to back out more results, you need to specify the size when you build Termsbuilder:
Termsbuilder teamagg= aggregationbuilders.terms ("Team"). Size (15);
resolution/output of 7.Aggregation resultsAfter getting response:
<span style= "White-space:pre" >	</span>map<string, aggregation> aggmap = Response.getaggregations (). Asmap ();
        Stringterms teamagg= (stringterms) aggmap.get ("Keywordagg");
        iterator<bucket> teambucketit = Teamagg.getbuckets (). iterator ();
        while (Teambucketit. Hasnext ()) {
            Bucket buck = teambucketit. Next ();
            Squad name
            String team = Buck.getkey ();
            Number of records
            Long Count = Buck.getdoccount ();
            Gets all the sub aggregates
            Map subaggmap = Buck.getaggregations (). Asmap ();
            Avg Value Get method
            double avg_age= ((INTERNALAVG) subaggmap.get ("Avg_age")). GetValue ();
            The sum value gets method
            Double total_salary = ((internalsum) subaggmap.get ("Total_salary")). GetValue ();
            //...
            Max/min, etc.
        }

8. SummaryIn summary, the aggregation operation is mainly called the Searchrequestbuilder addaggregation method, usually passing in a termsbuilder, the child aggregation calls the Termsbuilder Subaggregation method, The aggregations that can be added are common aggregation operations such as Termsbuilder, Sumbuilder, Avgbuilder, Maxbuilder, Minbuilder, and so on.
In terms of implementation, Searchrequestbuilder maintains a private Searchsourcebuilder instance internally, Searchsourcebuilder contains a list< Abstractaggregationbuilder&gt, the Searchsourcebuilder instance is invoked each time the addaggregation is invoked, and a aggregationbuilder is added. Likewise, Termsbuilder kept a list<abstractaggregationbuilder&gt inside; A aggregationbuilder is added when the Addaggregation method (from the parent class addaggregation) is invoked. Interested readers can also read the implementation of the source code.
If you have any questions, welcome to discuss with us, if there are any mistakes in the text, please comment.
Note: The elastic Search API version used in this article is 2.3.2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.