Elasticsearch 6.4 java

POM文件

 <dependency>
	<groupId>org.elasticsearch.client</groupId>
	<artifactId>transport</artifactId>
	<version>6.2.4</version>
</dependency>
 <dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.2.4</version>
</dependency> 

JAVA文件

http://www.cnblogs.com/xionggeclub/p/7975982.html

package com.es.util;

 import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.junit.Before;
import org.junit.Test;
 import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.nested.ReverseNested;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder.Order;
import org.elasticsearch.transport.client.PreBuiltTransportClient;


public class ElasticsearchQuery {
    private TransportClient client;

	  @Before 
	    public   void  testBefore() throws UnknownHostException {
	        client  = new PreBuiltTransportClient(Settings.EMPTY)
	                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
 	    }
	@Test
	public  void ElasticsearchQuery() throws Exception {
		/*
		 * 
		 * 插入数据
POST _bulk
{"index":{"_index":"cars","_type":"doc","_id":"1"}}
{"name":"bmw","date":"2017-06-01", "color":"red", "price":30000}
{"index":{"_index":"cars","_type":"doc","_id":"2"}}
{"name":"bmw","date":"2017-06-30", "color":"blue", "price":50000}
{"index":{"_index":"cars","_type":"doc","_id":"3"}}
{"name":"bmw","date":"2017-08-11", "color":"red", "price":90000}
{"index":{"_index":"cars","_type":"doc","_id":"4"}}
{"name":"ford","date":"2017-07-15", "color":"red", "price":20000}
{"index":{"_index":"cars","_type":"doc","_id":"5"}}
{"name":"ford","date":"2017-07-01", "color":"blue", "price":40000}
{"index":{"_index":"cars","_type":"doc","_id":"6"}}
{"name":"bmw","date":"2017-08-01", "color":"green", "price":10000}
{"index":{"_index":"cars","_type":"doc","_id":"7"}}
{"name":"jeep","date":"2017-07-08", "color":"red", "price":110000}
{"index":{"_index":"cars","_type":"doc","_id":"8"}}
{"name":"jeep","date":"2017-08-25", "color":"red", "price":230000}

		 * 
		 * 
		 * 
		 */
		
		
		
		
 		  //查询1
	    //GetResponse response = client.prepareGet("book", "it" ,"2").get();
        //System.out.println(response.getSourceAsString());

 
		//must 查询
		/*
		 * 
		  
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		boolQuery.must( QueryBuilders.rangeQuery("price").from(1).to(230000)
				).must(QueryBuilders.matchPhraseQuery("color", "red"));
          SearchRequestBuilder search =  client.prepareSearch("cars").setQuery(boolQuery);
         SearchResponse response = search.get(); 
         SearchHits hits = response.getHits();
         for(SearchHit hit:hits.getHits()){
             Map<String, Object> sourceMap = hit.getSourceAsMap();
              System.out.println( sourceMap.get("color"));
              System.out.println( sourceMap.get("price"));
         };
    	 */
          
	/**
	 * 	
	 DSL语句    按名称分组求平均价格
	 
	 POST cars/_search
         {
           "size": 0,
           "aggs": {
               "nametype":{
               "terms":{
                   "field":"name.keyword"
               },
               "aggs":{
               "avgprice":{
                 "avg":{
                 
                 "field":"price"
                 }
               }
               }
               }
            }
         }
	 * 
	 * 
	 */
         
 
         /**
          * 多字段上的聚合操作需要用到子聚合(subAggregation)
          */
         
	/**
	 * 	
	
		TermsAggregationBuilder  aggregation = AggregationBuilders
			    .terms("nametype").field("name.keyword").size(100).order(BucketOrder.aggregation("avg-price", false))
;//默认返回10条结果     按avg-price排序  false倒序,true正序
		
		AvgAggregationBuilder avgprice=  AggregationBuilders.avg("avg-price").field("price");
          
			QueryBuilder allQuery = QueryBuilders.matchAllQuery();
			
			SearchResponse response = client.prepareSearch("cars")
			     .setQuery(allQuery).addAggregation(aggregation.subAggregation(avgprice)).get();
			//根据别名获取聚合对象,不同聚合会返回不同的聚合对象
			Terms terms = response.getAggregations().get("nametype");
			
			terms.getBuckets().forEach(p->
			{
			    String value = p.getKey().toString();
			    //聚合后的数量
			    long count = p.getDocCount();
			    Avg  agg = p.getAggregations().get("avg-price");
			    double price = agg.getValue();
			    System.out.println(value);
			    System.out.println(count);
			    System.out.println(price);	
			});
			
		 */ 	
		
		
		
		/*
		 * gourp by   name,color
		 * 
		 */
		TermsAggregationBuilder teamAgg= AggregationBuilders.terms("name_type").field("name.keyword");
		TermsAggregationBuilder posAgg= AggregationBuilders.terms("color_type").field("color.keyword");
		QueryBuilder allQuery = QueryBuilders.matchAllQuery();

		SearchResponse response = client.prepareSearch("cars").setQuery(allQuery)
			     .addAggregation(teamAgg.subAggregation(posAgg)).get();
		
		
		Map<String, Aggregation> aggMap = response.getAggregations().asMap();
		StringTerms teams= (StringTerms) aggMap.get("name_type");
		teams.getBuckets().forEach(p->
		{
		    String value = p.getKey().toString();
		    //聚合后的数量
		    long count = p.getDocCount();
 		    System.out.println(value);
 		    
		    Map<String, Aggregation>  aggMap2=p.getAggregations().asMap();
		    
			StringTerms teams2= (StringTerms) aggMap2.get("color_type");
			
			teams2.getBuckets().forEach(t->
					{
					    String value2 = t.getKey().toString();
					    //聚合后的数量
					    long count2 = t.getDocCount();
			 		    System.out.print(" "+value2);
					    System.out.println(" "+count2);
						
					}
					
					
					);
			

		    
		    
		    
 		});
		 
		
         
             client.close();
             

	}
	
	
	
	
     
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值