import cn.jpush.statistics.elasticsearch.ReportDO;
import cn.jpush.statistics.util.JsonUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;
import org.joda.time.LocalDate;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
@Slf4j
public class EsClient {
public static void main(String[] args) throws UnknownHostException {
esSearch();
}
private static void esSearch() throws UnknownHostException {
//指定集群
Settings settings = Settings.builder().put("cluster.name", "elasticsearch").put("client.transport.sniff",false).build();
// 创建访问es的客户端
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9300));
// TermQueryBuilder query = QueryBuilders.termQuery("channel", "GDT");
BoolQueryBuilder query = QueryBuilders.boolQuery();
List<QueryBuilder> must = query.must();
must.add(QueryBuilders.termsQuery("channel", "GDT".toLowerCase()));
DateTime start = new DateTime(2017,1,1,0,0,0);
DateTime end = new DateTime(2020,9,1,0,0,0);
must.add(QueryBuilders.termQuery( "advertiser_id", 12));
must.add(QueryBuilders.termQuery( "product_id", 98));
RangeQueryBuilder rangeQueryBuilder = QueryBuilders
.rangeQuery("query_time")
.gt(start.getMillis())
.lte(end.getMillis())
.format("epoch_millis");
must.add(rangeQueryBuilder);
// must.add(QueryBuilders.termsQuery("advertiser_id", Lists.newArrayList(243)));
SearchRequestBuilder builder = client.prepareSearch("ad-report-v3-20*")
.setTypes("report")
.setQuery(query);
log.info("elastic.list.query.string: \n\n{}\n\n",builder.toString());
SearchResponse response = builder
// .setSize(3)
.get();
for (SearchHit hit : response.getHits()) {
String sourceAsString = hit.getSourceAsString();
ReportDO reportDO = JsonUtil.parseObject(sourceAsString, ReportDO.class);
System.out.println(JsonUtil.toJsonString(reportDO));
}
client.close();
}
}