赞
踩
<!--elasticsearch-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
注意${elasticsearch.version}的版本号与ElasticSearch版本号一致
package com.atguigu.gulimall.search.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GulimallElasticSearchConfig { //所有的RestHighLevelClient的API请求都要传入一个RequestOptions public static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); // 需要添加的头 // builder.addHeader("Authorization","Bearer " + token); // 异步请求设置 // builder.setHttpAsyncResponseConsumerFactory(); COMMON_OPTIONS = builder.build(); } @Bean public RestHighLevelClient esRestClient() { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"))); return client; } }
package com.atguigu.gulimall.search.crudTest; import com.alibaba.fastjson.JSON; import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig; import lombok.Data; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; @RunWith(SpringRunner.class) @SpringBootTest public class CrudTest { @Data class User { private String username; private String gender; private Integer age; } @Autowired private RestHighLevelClient esClient; /** * 创建、插入、更新 */ @Test public void testIndex() throws IOException { IndexRequest indexRequest = new IndexRequest("users"); // 数据id indexRequest.id("1"); User user = new User(); user.setAge(25); user.setGender("男"); user.setUsername("小明"); String userStr = JSON.toJSONString(user); indexRequest.source(userStr, XContentType.JSON); // 同步。可以创建索引,可以创建、更新文档 IndexResponse response = esClient.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS); System.out.println(JSON.toJSONString(response)); } }
说明:
(1)esClient.index是同步调用方法;
(2)当索引不存在时可以创建该索引,也可以用于更新文档;
# 搜索address中包含mill的所有人的年龄分布以及平均年龄 GET /bank/_search { "size": 0, "query": { "match": { "address": "mill" } }, "aggs": { "aggAge": { "terms": { "field": "age", "size": 100 } }, "aggAvg":{ "avg": { "field": "age" } } } }
输出:
{ "took" : 0, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 4, "relation" : "eq" }, "max_score" : null, "hits" : [ ] }, "aggregations" : { "aggAvg" : { "value" : 34.0 }, "aggAge" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : 38, "doc_count" : 2 }, { "key" : 28, "doc_count" : 1 }, { "key" : 32, "doc_count" : 1 } ] } } }
@Test public void testComplexIndex() throws IOException { SearchRequest searchRequest = new SearchRequest(); searchRequest.indices("bank"); //指定DSL,检索条件(searchSourceBuilder直接可以调用DSL中根一级的查询语句,比如query、from、size等) SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //1. 构造查询条件 searchSourceBuilder.size(0); searchSourceBuilder.query(QueryBuilders.matchQuery("address", "mill")); //2. 按照年龄的值进行聚合 TermsAggregationBuilder termAgg = AggregationBuilders.terms("aggAge").field("age").size(100); searchSourceBuilder.aggregation(termAgg); //3. 计算平均年龄 AvgAggregationBuilder aggAvg = AggregationBuilders.avg("aggAvg").field("age"); searchSourceBuilder.aggregation(aggAvg); searchRequest.source(searchSourceBuilder); System.out.println("检索条件:" + searchSourceBuilder.toString()); SearchResponse searchResponse = esClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS); System.out.println("响应结果:" + searchResponse.toString()); Aggregations aggregations = searchResponse.getAggregations(); Terms aggAgeResponse = aggregations.get("aggAge"); for (Terms.Bucket bucket : aggAgeResponse.getBuckets()) { String key = bucket.getKeyAsString(); Long count = bucket.getDocCount(); System.out.println("key:>>" + key + " count:>>" + count); } Avg aggAvgResponse = aggregations.get("aggAvg"); System.out.println("aggAvgValue:>>" + aggAvgResponse.getValue()); }
输出:
检索条件:{"size":0,"query":{"match":{"address":{"query":"mill","operator":"OR","prefix_length":0,"max_expansions":50,"fuzzy_transpositions":true,"lenient":false,"zero_terms_query":"NONE","auto_generate_synonyms_phrase_query":true,"boost":1.0}}},"aggregations":{"aggAge":{"terms":{"field":"age","size":100,"min_doc_count":1,"shard_min_doc_count":0,"show_term_doc_count_error":false,"order":[{"_count":"desc"},{"_key":"asc"}]}},"aggAvg":{"avg":{"field":"age"}}}}
响应结果:{"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":4,"relation":"eq"},"max_score":null,"hits":[]},"aggregations":{"avg#aggAvg":{"value":34.0},"lterms#aggAge":{"doc_count_error_upper_bound":0,"sum_other_doc_count":0,"buckets":[{"key":38,"doc_count":2},{"key":28,"doc_count":1},{"key":32,"doc_count":1}]}}}
key:>>38 count:>>2
key:>>28 count:>>1
key:>>32 count:>>1
aggAvgValue:>>34.0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。