ElasticSearch之JavaAPI使用
ElasticSearch之JavaAPI使用
Java High Level REST Client ——Api使用
//使用spring驱动跑测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {@AutowiredRestHighLevelClient restHighLevelClient;@Testpublic void contextLoads() {System.out.println(restHighLevelClient);}/*** GET /bank/_search* {* "query": {* "match": {* "address": "mill"* }* },* "aggs": {* "ageAggs": {* "terms": {* "field": "age",* "size": 10* },* "aggs": {* "banlanceAggs": {* "avg": {* "field": "balance"* }* }* }* }* }* }*///检索请求@Testpublic void search() throws IOException {SearchRequest searchRequest = new SearchRequest("bank");//bank:索引 GET /bank/_searchSearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//matchsearchSourceBuilder.query(QueryBuilders.matchQuery("address","mill"));//aggsTermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("ageAggs").field("age").size(10)//子聚合.subAggregation(AggregationBuilders.avg("banlanceAggs").field("balance"));//把聚合装入SearchSourceBuildersearchSourceBuilder.aggregation(termsAggregationBuilder);//装入检索条件searchRequest.source(searchSourceBuilder);//public final SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException {SearchResponse searchResponse = restHighLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);//分析结果
// System.out.println(searchResponse.toString());SearchHit[] hits = searchResponse.getHits().getHits();//1.获取hit数据for (SearchHit hit : hits) {//拿到Json字符串String sourceAsString = hit.getSourceAsString();//json字符串转java对象//如果使用内部类进行json序列化,会因为找不到它的外部类而报异常,如果内部类是静态的,里面没有默认的外部类的引用,在json转换的时候不会报错JsonRootBean jsonRootBean = JSON.parseObject(sourceAsString, JsonRootBean.class);System.out.println("jsonRootBean对象" + jsonRootBean);}//2.获取aggs聚合数据Aggregations aggregations = searchResponse.getAggregations();// Aggregation ageAggs = aggregations.get("ageAggs");//聚合类型Terms,AvgTerms ageAggs = aggregations.get("ageAggs");for (Terms.Bucket bucket : ageAggs.getBuckets()) {//平均年龄聚合String keyAsString = bucket.getKeyAsString();//获取子聚合Aggregations aggregations1 = bucket.getAggregations();Avg balanceAvg = aggregations1.get("banlanceAggs");System.out.println("平均年龄聚合:" + keyAsString + ",平均年龄薪资聚合:" + balanceAvg.getValue());}}//内部类必须是静态/*** 主要是因为Java内部类和嵌套类的实现机制造成的,首先按照Java编程思想的说法,* 静态的内部类叫做嵌套类,那么两者有什么区别呢?一般的内部类虽然在源代码中没有写,* 但是编译后会看到里面多了一个指向外部类的引用,如果使用内部类进行json序列化,* 会因为找不到它的外部类而报异常,而嵌套类因为是静态的,里面没有默认的外部类的引用,* 即使没有外部类的对象也能够使用,因此在json转换的时候不会报错*/@ToString@Datapublic static class JsonRootBean {private int account_number;private int balance;private String firstname;private String lastname;private int age;private String gender;private String address;private String employer;private String email;private String city;private String state;}//往es中存入数据@Testpublic void indexDate() throws IOException {IndexRequest indexRequest = new IndexRequest();indexRequest.id("1");//索引名indexRequest.index("user");User user = new User();user.setName("闰土");user.setAge(23L);user.setAddress("三峡文化城");String jsonString = JSON.toJSONString(user);indexRequest.source(jsonString, XContentType.JSON);//public final IndexResponse index(IndexRequest indexRequest, RequestOptions options)//同步执行IndexResponse indexResponse = restHighLevelClient.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);System.out.println(indexResponse);restHighLevelClient.close();}@Datapublic class User{private String name;private Long age;private String address;}}
ElasticSearch配置类
@Configuration
public class GulimallElasticSearchConfig {@Beanpublic RestHighLevelClient esRestClient(){RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.56.10", 9200, "http")));return client;}//es有安全访问规则,,请求访问es必须携带安全请求头public static final RequestOptions COMMON_OPTIONS;static {RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// builder.addHeader("Authorization", "Bearer " + TOKEN);//TOKEN 添加所有请求所需的任何标头
// builder.setHttpAsyncResponseConsumerFactory(//自定义响应使用者
// new HttpAsyncResponseConsumerFactory
// .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));COMMON_OPTIONS = builder.build();}}
Kibana
DSL
GET /bank/_search
{"query": {"match": {"address": "mill"}},"aggs": {"ageAggs": {"terms": {"field": "age","size": 10},"aggs": {"banlanceAggs": {"avg": {"field": "balance"}}}}}
}
检索结果
{"took" : 1,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 4,"relation" : "eq"},"max_score" : 5.4032025,"hits" : [{"_index" : "bank","_type" : "account","_id" : "970","_score" : 5.4032025,"_source" : {"account_number" : 970,"balance" : 19648,"firstname" : "Forbes","lastname" : "Wallace","age" : 28,"gender" : "M","address" : "990 Mill Road","employer" : "Pheast","email" : "forbeswallace@pheast","city" : "Lopezo","state" : "AK"}},{"_index" : "bank","_type" : "account","_id" : "136","_score" : 5.4032025,"_source" : {"account_number" : 136,"balance" : 45801,"firstname" : "Winnie","lastname" : "Holland","age" : 38,"gender" : "M","address" : "198 Mill Lane","employer" : "Neteria","email" : "winnieholland@neteria","city" : "Urie","state" : "IL"}},{"_index" : "bank","_type" : "account","_id" : "345","_score" : 5.4032025,"_source" : {"account_number" : 345,"balance" : 9812,"firstname" : "Parker","lastname" : "Hines","age" : 38,"gender" : "M","address" : "715 Mill Avenue","employer" : "Baluba","email" : "parkerhines@baluba","city" : "Blackgum","state" : "KY"}},{"_index" : "bank","_type" : "account","_id" : "472","_score" : 5.4032025,"_source" : {"account_number" : 472,"balance" : 25571,"firstname" : "Lee","lastname" : "Long","age" : 32,"gender" : "F","address" : "288 Mill Street","employer" : "Comverges","email" : "leelong@comverges","city" : "Movico","state" : "MT"}}]},"aggregations" : {"ageAggs" : {"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : 38,"doc_count" : 2,"banlanceAggs" : {"value" : 27806.5}},{"key" : 28,"doc_count" : 1,"banlanceAggs" : {"value" : 19648.0}},{"key" : 32,"doc_count" : 1,"banlanceAggs" : {"value" : 25571.0}}]}}
}
最新文章
- matlab 回归分析t检验,第三章 利用Matlab和SPSS进行线性回归分析
- digest介绍
- java.lang.NullPointerException: null
- Tensorflow框架初识
- 大型高并发高负载网站的系统架构[转载]
- GridView
- MinGW+MSYS安装
- 网络Socket编程
- 数字化原理
- 软件兼容性与软件兼容性测试
- 网络设备流量及性能监控的实现
- SVM算法实现(一)
- matlab自带的插值函数interp1的四种插值方法
- const和extern用法
- 集合类 CList的使用
- shiro反序列化漏洞学习(工具+原理+复现)
- 自适应直方图均衡(CLAHE) 代码及详细注释【OpenCV】