Elasticsearch5.0 Java Api(八) -- 常用DSL查询

  测试常用的DSL组合查询功能

  1 package com.juyun.test;
  2
  3 import java.net.InetAddress;
  4
  5 import org.elasticsearch.action.search.SearchResponse;
  6 import org.elasticsearch.client.Client;
  7 import org.elasticsearch.common.settings.Settings;
  8 import org.elasticsearch.common.transport.InetSocketTransportAddress;
  9 import org.elasticsearch.index.query.QueryBuilder;
 10 import org.elasticsearch.index.query.QueryBuilders;
 11 import org.elasticsearch.search.SearchHit;
 12 import org.elasticsearch.search.SearchHits;
 13 import org.elasticsearch.search.aggregations.AggregationBuilder;
 14 import org.elasticsearch.search.aggregations.AggregationBuilders;
 15 import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
 16 import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
 17 import org.elasticsearch.search.sort.SortBuilder;
 18 import org.elasticsearch.search.sort.SortBuilders;
 19 import org.elasticsearch.search.sort.SortOrder;
 20 import org.elasticsearch.transport.client.PreBuiltTransportClient;
 21 import org.joda.time.DateTimeZone;
 22
 23 public class DslQuery {
 24
 25     private static Client client;
 26
 27     // 测试时常用的几种dsl
 28     public static void main(String[] args) {
 29
 30         try {
 31             // 设置集群名称
 32             Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
 33             // 创建client
 34             client = new PreBuiltTransportClient(settings)
 35                     .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("172.16.0.157"), 9300));
 36
 37             long startTime=System.currentTimeMillis(); // 获取开始时间
 38
 39             commonQuery("newindex","newhttp");
 40             //commonQuery2("newindex","newhttp");
 41
 42             long endTime=System.currentTimeMillis(); //获取结束时间
 43             System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
 44
 45
 46             // 关闭client
 47             client.close();
 48
 49         } catch (Exception e) {
 50             e.printStackTrace();
 51         }
 52     }
 53
 54     /**
 55      * 以时间戳降序排列并查询出所有数据
 56      * @param indexName
 57      * @param typeName
 58      */
 59     public static void commonQuery(String indexName, String typeName){
 60
 61         SortBuilder sortBuilder = SortBuilders.fieldSort("@timestamp")
 62                 .order(SortOrder.DESC).unmappedType("boolean"); // 定义排序方式
 63         QueryBuilder queryBuilder =QueryBuilders.boolQuery()
 64                 .must(QueryBuilders.queryStringQuery("*").analyzeWildcard(true).defaultField("_all")); // 定义查询方式
 65
 66         SearchResponse searchResponse = client.prepareSearch(indexName).setTypes(typeName)
 67                 .setQuery(queryBuilder)
 68                 .addSort(sortBuilder)
 69                 .setSize(500)
 70                 .execute().actionGet();
 71
 72         SearchHits hits = searchResponse.getHits(); // 获取搜索结果
 73         for (SearchHit searchHit : hits) {    // 遍历并以字符串形式打印搜索结果
 74             System.out.println(searchHit.getSourceAsString());
 75         }
 76         System.out.println("查询到记录数:" + hits.getTotalHits());
 77     }
 78
 79
 80     /**
 81      * 集合查询统计总值
 82      * @param indexName
 83      * @param typeName
 84      */
 85     public static void commonQuery2(String indexName, String typeName){
 86
 87         SortBuilder sortBuilder = SortBuilders.fieldSort("@timestamp")
 88                 .order(SortOrder.DESC).unmappedType("boolean"); // 定义排序方式
 89         QueryBuilder queryBuilder =QueryBuilders.boolQuery()
 90                 .must(QueryBuilders.queryStringQuery("*").analyzeWildcard(true).defaultField("_all")); // 定义查询方式
 91
 92         AggregationBuilder aggBuilder1=AggregationBuilders.dateHistogram("dateagg") // 定义时间间隔直方图
 93                 .field("@timestamp")
 94                 .dateHistogramInterval(DateHistogramInterval.minutes(1))
 95                 .timeZone(DateTimeZone.forID("+08:00"));
 96
 97         AggregationBuilder aggBuilder2=AggregationBuilders.sum("sumOfOut").field("http.bytes_out"); // 聚合统计
 98         AggregationBuilder aggBuilder3=AggregationBuilders.sum("sumOfIn").field("http.bytes_in");
 99
100         SearchResponse searchResponse = client.prepareSearch(indexName).setTypes(typeName)
101                 .setQuery(queryBuilder)
102                 .addSort(sortBuilder)
103                 .addAggregation(aggBuilder1)
104                 .addAggregation(aggBuilder2)
105                 .addAggregation(aggBuilder3)
106                 .setSize(500)
107                 .execute().actionGet();
108
109         SearchHits hits = searchResponse.getHits(); // 获取搜索结果
110         for (SearchHit searchHit : hits) {    // 遍历并以字符串形式打印搜索结果
111             System.out.println(searchHit.getSourceAsString());
112         }
113         InternalSum sumOfOut = searchResponse.getAggregations().get("sumOfOut"); // 获取出流量总值
114         InternalSum sumOfIn = searchResponse.getAggregations().get("sumOfIn"); // 获取进流量总值
115
116         System.out.println("查询到记录数:" + hits.getTotalHits());
117         System.out.println("outbyte的总值是:"+sumOfOut.getValue());
118         System.out.println("inbyte的总值是:"+sumOfIn.getValue());
119     }
120 }

DslQuery

时间: 2024-12-09 22:07:13

Elasticsearch5.0 Java Api(八) -- 常用DSL查询的相关文章

Elasticsearch5.0 Java Api(一) -- 插入索引

Elasticsearch5.X官方手册 Elasticsearch5.X官方手册中文版 Elasticsearch5.X Java Api官方手册 导入maven依赖 <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.0.0</version> </depend

Elasticsearch5.0 Java Api(七) -- 聚合查询

测试聚合查询功能 1 package com.juyun.test; 2 3 import java.net.InetAddress; 4 import java.util.List; 5 6 import org.elasticsearch.action.search.SearchResponse; 7 import org.elasticsearch.client.Client; 8 import org.elasticsearch.common.settings.Settings; 9 i

Elasticsearch5.0 Java Api(四) -- 检索索引

测试检索索引库的功能 1 package com.juyun.test; 2 3 import java.net.InetAddress; 4 5 import org.elasticsearch.client.Client; 6 import org.elasticsearch.common.settings.Settings; 7 import org.elasticsearch.common.transport.InetSocketTransportAddress; 8 import or

Elasticsearch5.0 Java Api(三) -- 删除索引

测试删除索引的功能 1 package com.juyun.test; 2 3 import java.net.InetAddress; 4 import java.net.UnknownHostException; 5 6 import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; 7 import org.elasticsearch.action.admin.indices.create.CreateInd

Elasticsearch5.0 Java Api(二) -- 更新索引

elasticsearch提供了多种更新索引的方式,这里简单介绍其中五种 1 package com.juyun.test; 2 3 import java.io.IOException; 4 import java.net.InetAddress; 5 import java.util.concurrent.ExecutionException; 6 7 import org.elasticsearch.action.index.IndexRequest; 8 import org.elast

Elasticsearch5.0 Java Api(六) -- 批量导入索引

将计算机本地的.json格式文件中的数据,批量导入到索引库中 1 package com.juyun.test; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileNotFoundException; 6 import java.io.FileReader; 7 import java.io.IOException; 8 import java.net.InetAddress; 9 imp

Elasticsearch5.0 Java Api(五) -- 批量导出索引

从索引库中将检索到的数据导出到外部文件,文件格式为.json 1 package com.juyun.test; 2 3 import java.io.BufferedWriter; 4 import java.io.File; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.net.InetAddress; 8 import java.net.UnknownHostException; 9 10

elasticsearch-5.x JAVA API(002)

elasticsearch-5.x JAVA API 第二部分:集群健康与段合并 1. 集群健康 首先定义一个类来存储集群健康信息 package com.zw.elasticsearch.cluster; public class ClusterHealth { // 集群名 private String clusterName; // 集群中节点数目 private int number_of_node; // 活跃总分片数目 private int number_of_activeShar

Elasticsearch Java API(八)--搜索有相同父id的子文档

需求: 搜索具有相同父id的所有子文档. 数据:    mapping:      { "mappings": { "branch": {}, "employee": { "_parent": { "type": "branch" } } } } 父文档: { "index": { "_id": "london" }} { &q