ElasticSearch基础 java操作es归纳
java操作es有2种方式:
1.通过9300端口 tcp ransport-api.jar 但不能适配版本 不建议使用
2.通过9200端口 http Elasticsearch-Rest-Client 官方restclient 建议使用
导入依赖
//导入依赖 <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.4.2</version> </dependency> //导入的版本与es版本一致7.4.2 //打开maven插件看dependencies中管理的依赖es版本是7.9.3 //因为springboot已经对es的版本做了管理 xml重写下es版本 <properties> <java.version>1.8</java.version> <elasticsearch.version>7.4.2</elasticsearch.version> </properties> springboot中es版本也改过来了
配置es
//类似数据库dao配置 代码通用的 @Configuration public class GuliESConfig { public static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); COMMON_OPTIONS = builder.build(); } @Bean public RestHighLevelClient esRestClient() { RestClientBuilder builder = null; // 可以指定多个es builder = RestClient.builder(new HttpHost("192.168.112.151", 9200, "http") // ,new HttpHost("host", 9200, "http") ); RestHighLevelClient client = new RestHighLevelClient(builder); return client; } } //其它代码用到es注入就行了 @Autowired private RestHighLevelClient esRestClient;
java es保存测试 IndexRequest
@Autowired private RestHighLevelClient esRestClient; /** * 保存数据 * @throws IOException */ @Test void indexData() throws IOException{ //设置保存的索引和id IndexRequest indexRequest = new IndexRequest("users"); indexRequest.id("1"); //保存的数据 这里指定json类型 indexRequest.source("{\"test\":1}", XContentType.JSON); //执行保存 index同步 indexAsync异步 IndexResponse index = esRestClient.index(indexRequest, GuliESConfig.COMMON_OPTIONS); System.out.println(index); }
java es 检索测试 SearchRequest
相当查询 "query": { "match": { "address": "Mill" } }
@Test public void find() throws IOException { // 1 创建检索请求 SearchRequest searchRequest = new SearchRequest(); searchRequest.indices("bank"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 构造检索条件 // sourceBuilder.query(); // sourceBuilder.from(); // sourceBuilder.size(); // sourceBuilder.aggregation(); sourceBuilder.query(QueryBuilders.matchQuery("address","mill")); System.out.println(sourceBuilder.toString()); searchRequest.source(sourceBuilder); // 2 执行检索 SearchResponse response = esRestClient.search(searchRequest, GuliESConfig.COMMON_OPTIONS); // 3 分析响应结果 System.out.println(response.toString()); }
查询结果转为bean
// 3.1 获取java bean Account是bean类 SearchHits hits = response.getHits(); SearchHit[] hits1 = hits.getHits(); for (SearchHit hit : hits1) { hit.getId(); hit.getIndex(); String sourceAsString = hit.getSourceAsString(); Account account = JSON.parseObject(sourceAsString, Account.class); System.out.println(account); }
聚合检索测试
搜索address中包含mill的所有人的年龄分布以及平均年龄,平均薪资
GET bank/_search { "query": { "match": { "address": "Mill" } }, "aggs": { "ageAgg": { "terms": { "field": "age", "size": 10 } }, "ageAvg": { "avg": { "field": "age" } }, "balanceAvg": { "avg": { "field": "balance" } } } }
java代码测试如下
/** * 聚合检索 * @throws IOException */ @Test public void jhfind() throws IOException { // 1 创建检索请求 SearchRequest searchRequest = new SearchRequest(); searchRequest.indices("bank"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 构造检索条件 // sourceBuilder.query(); // sourceBuilder.from(); // sourceBuilder.size(); // sourceBuilder.aggregation(); sourceBuilder.query(QueryBuilders.matchQuery("address","mill")); //AggregationBuilders工具类构建AggregationBuilder // 构建第一个聚合条件:按照年龄的值分布 TermsAggregationBuilder agg1 = AggregationBuilders.terms("agg1").field("age").size(10);// 聚合名称 // 参数为AggregationBuilder sourceBuilder.aggregation(agg1); // 构建第二个聚合条件:平均薪资 AvgAggregationBuilder agg2 = AggregationBuilders.avg("agg2").field("balance"); sourceBuilder.aggregation(agg2); System.out.println("检索条件"+sourceBuilder.toString()); searchRequest.source(sourceBuilder); // 2 执行检索 SearchResponse response = esRestClient.search(searchRequest, GuliESConfig.COMMON_OPTIONS); // 3 分析响应结果 System.out.println(response.toString()); }
检索结果处理
// 3.2 获取检索到的分析信息 //实际测试检索结果aggregations下名称不是"agg2"而是"avg#agg2" 不是"agg1"而是"lterms#agg1" 暂不知道是什么原因 先记录着 Aggregations aggregations = response.getAggregations(); Terms agg21 = aggregations.get("agg2"); //"avg#agg2" for (Terms.Bucket bucket : agg21.getBuckets()) { String keyAsString = bucket.getKeyAsString(); System.out.println(keyAsString); }