- 浏览: 622146 次
- 性别:
- 来自: 杭州
文章分类
- 全部博客 (334)
- java core (12)
- struts2.x (2)
- spring (3)
- hibernate (8)
- jpa (6)
- maven (2)
- osgi (5)
- eclipse (4)
- struts2.x+spring2.x+hibernate 整合 (5)
- ebs (0)
- html (0)
- vaadin (1)
- css (0)
- jquery (0)
- javascript (0)
- svn (1)
- cvs (0)
- axas2.x (0)
- eclipse+maven (9)
- annotation (0)
- 基于OSGi的动态化系统搭建 (1)
- notenet (1)
- jboss eclipse (4)
- eclipse工具 (4)
- jdk1.6+maven3.0.3+nuxeo+svn+felix+cxf+spring+springDM (6)
- spring dm (1)
- Nexus介绍 (1)
- proxool listener (0)
- oracle (4)
- mysql (8)
- 搭建你的全文检索 (1)
- hibernatehibernatehibernate (0)
- cvsearchcvsearch (0)
- mycvseach (0)
- asdfasdfasdf (0)
- propertiey (0)
- hibernate annotation (0)
- libs (0)
- icam (2)
- start 数据库配置 (0)
- jboss (1)
- 让Eclipse启动时显示选择workspace的对话框 (1)
- table表头固定 (1)
- s2s3h4 (0)
- leaver (0)
- mycvsaerchddd (0)
- 关于jboss5.0.1部署 (4)
- bookmarks (0)
- PersistenceUnitDeployment (0)
- mycom (0)
- HKEY_CURRENT_USER = &H80000001 (0)
- syspath (1)
- css div (1)
- Dreamweaver CS5 (0)
- generate (0)
- mysql查看表结构命令 (1)
- LOG IN ERROR EMAIL TO SB (0)
- struts2 handle static resource (1)
- jsf (2)
- log4j (1)
- jbpm4.4 (2)
- down: jbpm4.4 (1)
- jstl1.2 (1)
- spring annotation (1)
- java design pattern (1)
- cache (1)
- ehcache (1)
- 11111 (0)
- myge (0)
- pom.xml (0)
- springquartz (0)
- OpenStack (9)
- hadoop (2)
- nginx (1)
- hadoop openstack (1)
- os (1)
- hadoop-2.6.0 zookeeper-3.4.6 hbase-0.98.9-hadoop2 集群 (5)
- hadoop2.7.0 ha Spark (2)
- tess (0)
- system (1)
- asdf (0)
- hbase (2)
- hbase create table error (1)
- ekl (1)
- gitignore (1)
- gitlab-ci.yml (1)
- shell (1)
- elasticsearch (2)
- Azkaban 3.0+ (1)
- centos用命令 (1)
- hive (1)
- kafka (1)
- CaptureBasic (0)
- CentOS7 (1)
- dev tools (1)
- README.md (1)
- Error (1)
- teamviewerd.service (1)
- scala (1)
- spark (1)
- standard (1)
- gitlab (1)
- IDEA (0)
- ApplicationContext (1)
- 传统数仓 (1)
- redis install (1)
- MYSQL AND COLUME (1)
- java版本选择 (1)
- hue (1)
- npm (1)
- es (1)
- 版本管理 (1)
- 升级npm版本 (1)
- git (1)
- 服务器参数设置 (1)
- 调大 IDEA 编译内存大小 (0)
- CentOS8安装GitLab (1)
- gitlab安装使用 (1)
最新评论
-
ssydxa219:
vim /etc/security/limits.confvi ...
ekl -
Gamehu520:
table中无数据
hbase 出现的问题 -
Xleer0102:
为什么都是只有问没有答,哭晕在厕所
hbase 出现的问题 -
jiajiao_5413:
itext table -
CoderDream:
不完整,缺com.tcs.org.demostic.pub.u ...
struts2.3.1.1+hibernate3.6.9Final+spring3.1.0+proxool+maven+annotation
package com.wugui.eswr;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
private static String scheme = "http";
private static String host = "202.107.24.16";
private static int port = 9201;
private static String username = "elas918273";
private static String password = "Elastic#@!123";
private static String auth = "Authorization Type : Basic Auth";
private static String _index = ".security-7";
private static String _type = "_doc";
public static RestHighLevelClient esClient = null;
private static RequestOptions COMMON_OPTIONS = null;
public static RestHighLevelClient ESClientInit() {
//不需要用户名和密码的认证
//esClient = new RestHighLevelClient(RestClient.builder(new HttpHost(hostname, port, scheme)));
//需要用户名和密码的认证
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(host, port, scheme))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
esClient = new RestHighLevelClient(restClientBuilder);
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
builder.setHttpAsyncResponseConsumerFactory(
// 设置查询内容大小限制,默认100 * 1024 * 1024
new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(200 * 1024 * 1024)
);
COMMON_OPTIONS = builder.build();
return esClient;
}
public static void main(String[] args) throws Exception {
//queryAllByHits(ESClientInit());
queryAllByScollData(ESClientInit());
}
/**
* 创建索引
*
* @param esClient
* @throws Exception
*/
public static void indexCreate(RestHighLevelClient esClient) throws Exception {
//创建索引
CreateIndexRequest request = new CreateIndexRequest(".securityxxx-7");
CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);
//拿到响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作: " + acknowledged);
//关闭客户端连接
esClient.close();
}
/**
* 获取索引信息
*
* @param esClient
* @throws Exception
*/
public static void indexQuery(RestHighLevelClient esClient) throws Exception {
//创建索引连接
GetIndexRequest request = new GetIndexRequest(".security-7");
GetIndexResponse getIndexResponse = esClient.indices().get(request, RequestOptions.DEFAULT);
System.out.println("索引查询: " + getIndexResponse.getAliases());
System.out.println("索引查询: " + getIndexResponse.getMappings());
System.out.println("索引查询: " + getIndexResponse.getSettings());
//关闭客户端连接
esClient.close();
}
/**
* @param esClient
* @throws Exception
*/
private static void queryALl(RestHighLevelClient esClient) throws Exception {
//查询索引中的全部数据
SearchRequest request = new SearchRequest();
request.indices(".security-7");
//查询全部 matchAll
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 条件查询
*
* @param esClient
* @throws Exception
*/
private static void queryCondition(RestHighLevelClient esClient) throws Exception {
//查询索引中的全部数据
SearchRequest request = new SearchRequest();
request.indices("user");
//分词中 同时包含李强才可以,因为底层默认使用英文分词器,所以李强会被分为 李,强没办法符合条件所以查询不到
//request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("name","李强")));
//这样是李强字段不可再分,查询name字段中包含此字段的数据
request.source(new SearchSourceBuilder().query(QueryBuilders.matchPhraseQuery("name", "李强")));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 分页查询、部分字段显示、排序
*
* @param esClient
* @throws Exception
*/
private static void queryPage(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices(".security-7");
//构造查询条件 "match_all", "{}"
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//分页
query.from(0); //从第几条数据开始截取 (页码-1)* 每页数量
query.size(2); //每页的数量
String[] excludes = {"name"}; //排除字段
String[] includes = {"tel"}; //展示字段
query.fetchSource(includes, excludes);
//排序
query.sort("create_time", SortOrder.ASC);
request.source(query);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 组合条件查询
*
* @param esClient
* @throws Exception
*/
private static void queryConditionS(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//组合条件查询
//与
// boolQueryBuilder.must(QueryBuilders.matchQuery("name","小"));
// boolQueryBuilder.must(QueryBuilders.matchQuery("sex","性别1"));
// boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex","性别1"));
//或
boolQueryBuilder.should(QueryBuilders.matchQuery("name", "华"));
boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
//排序
builder.sort("tel", SortOrder.ASC);
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 范围查询
*
* @param esClient
* @throws Exception
*/
private static void queryBetween(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
rangeQueryBuilder.gte(30);
rangeQueryBuilder.lte(32);
//排序
builder.sort("tel", SortOrder.ASC);
builder.query(rangeQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 模糊查询(不针对中文)
*
* @param esClient
* @throws Exception
*/
private static void queryLike(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.fuzzyQuery("name", "zhangsan").fuzziness(Fuzziness.ONE));
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 高亮查询
*
* @param esClient
* @throws Exception
*/
private static void queryHighLighter(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhang");
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<h1 color='red'>");
highlightBuilder.postTags("</h1>");
highlightBuilder.field("name");
builder.highlighter(highlightBuilder);
builder.query(termQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 聚合查询(最大值)
*
* @param esClient
* @throws Exception
*/
private static void queryAggregation(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
//分组名称,聚合字段
AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
System.out.println(response);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 聚合查询(group分组)
*
* @param esClient
* @throws Exception
*/
private static void queryGroup(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
System.out.println(response);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 查询全部
*/
private static void queryAllByHits(RestHighLevelClient esClient) throws IOException {
Gson gson = new Gson();
// 创建搜索对象
SearchRequest searchRequest = new SearchRequest();
// 查询构建工具
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//排序
//No mapping found for [create_time] in order to sort on
//searchSourceBuilder.sort("create_time", SortOrder.ASC);
// 添加查询条件,通过QueryBuilders获取各种查询
searchSourceBuilder.query(QueryBuilders.matchAllQuery());//"match_all", "{}"
searchRequest.source(searchSourceBuilder);
// 搜索
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
// 解析
SearchHits hits = search.getHits();
SearchHit[] hits1 = hits.getHits();
for (SearchHit hit : hits1) {
// 取出source数据
String itemstring = hit.getSourceAsString();
// 反序列化
HashMap item = gson.fromJson(itemstring, HashMap.class);
System.out.println(item);
}
}
private static void queryAllByScoll1(RestHighLevelClient esClient) throws IOException {
try {
long startTime = System.currentTimeMillis();
/*创建客户端*/
//client startup
//设置集群名称
Settings settings = Settings.builder()
.put("cluster.name", "elsearch")
.put("client.transport.sniff", true)
.build();
//创建client
RestHighLevelClient client = esClient;
List<String> result = new ArrayList<>();
String scrollId = "";
//第一次请求
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//TODO: 设置查询条件
RangeQueryBuilder rangequerybuilder = QueryBuilders
.rangeQuery("inputtime")
.from("2016-12-14 02:00:00").to("2016-12-14 07:59:59");
sourceBuilder.query(QueryBuilders.boolQuery()
.must(QueryBuilders
.matchPhraseQuery("pointid", "W3.UNIT1.10HFC01CT013"))
.must(rangequerybuilder))
.size(100)//如果开启游标,则滚动获取
.sort("inputtime", SortOrder.ASC);
//查询
SearchRequest request = Requests.searchRequest("pointdata");
request.scroll("2m");
request.source(sourceBuilder);
SearchResponse response = client.search(request,null);//.actionGet();
//TODO:处理数据
SearchHits hits = response.getHits();
for (int i = 0; i < hits.getHits().length; i++) {
//System.out.println(hits.getHits()[i].getSourceAsString());
result.add(hits.getHits()[i].getSourceAsString());
}
//记录滚动ID
scrollId = response.getScrollId();
while (true) {
//后续的请求
//scrollId = query.getScollId();
SearchScrollRequestBuilder searchScrollRequestBuilder = null;//client.prepareSearchScroll(scrollId);
// 重新设定滚动时间
//TimeValue timeValue = new TimeValue(30000);
searchScrollRequestBuilder.setScroll("2m");
// 请求
SearchResponse response1 = searchScrollRequestBuilder.get();
//TODO:处理数据
SearchHits hits2 = response1.getHits();
if (hits2.getHits().length == 0) {
break;
}
for (int i = 0; i < hits2.getHits().length; i++) {
result.add(hits2.getHits()[i].getSourceAsString());
}
//下一批处理
scrollId = response1.getScrollId();
}
System.out.println(result.size());
long endTime = System.currentTimeMillis();
System.out.println("Java程序运行时间:" + (endTime - startTime) + "ms");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void queryAllByScoll(RestHighLevelClient esClient) throws IOException {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.should(QueryBuilders.termQuery("match_all","{}"));
// 存活时间,当索引数据量特别大时,出现超时可能性大,此值适当调大
Scroll scroll = new Scroll(TimeValue.timeValueMinutes(10L));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(boolQuery);
searchSourceBuilder.size(5);
SearchRequest searchRequest = new SearchRequest()
// ES7已经去掉type,查询时加type
.indices(_index)
.scroll(scroll)
.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try{
searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
} catch(
IOException e) {
e.printStackTrace();
}
String scrollId = searchResponse.getScrollId();
SearchHit[] searchHits = searchResponse.getHits().getHits();
for(SearchHit searchHit :searchHits){
System.out.println(searchHit.getSourceAsString());
}
//遍历搜索命中的数据,直到没有数据
while(searchHits !=null&&searchHits.length >0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
try {
searchResponse = esClient.scroll(scrollRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
scrollId = searchResponse.getScrollId();
searchHits = searchResponse.getHits().getHits();
if (searchHits != null && searchHits.length > 0) {
for (SearchHit searchHit : searchHits) {
System.out.println(searchHit.getSourceAsString());
}
}
}
//clean scroll
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(scrollId);
ClearScrollResponse clearScrollResponse = null;
try{
clearScrollResponse = esClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
} catch(
IOException e) {
//log.error("clear-scroll-error:{}", e);
}
boolean succeeded = clearScrollResponse.isSucceeded();
System.out.println(succeeded);
}
public static void queryAllByScollData(RestHighLevelClient esClient) throws IOException {
int i = 1,size = 2000,total = 43316300;
for(i=909 ; i<total/size ; i++) {
SearchRequest searchRequest = new SearchRequest();
//Scroll scroll = new Scroll(TimeValue.timeValueMinutes(5L));
//searchRequest.scroll(scroll);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
searchSourceBuilder.query(matchAllQueryBuilder);
searchSourceBuilder.from(i*size);
searchSourceBuilder.size(size);
searchRequest.source(searchSourceBuilder);
SearchResponse response = esClient.search(searchRequest, COMMON_OPTIONS);
//String scrollId = response.getScrollId();
SearchHit[] searchHits = response.getHits().getHits();
//System.out.println(response.getHits().getTotalHits());
for (SearchHit searchHit : searchHits) {
//System.out.println(searchHit.getSourceAsString());
FileUtil.appendString(searchHit.getSourceAsString()+"\n",new File("D:\\aa\\"+i*size+".csv"),"UTF-8");
}
/*while (searchHits != null && searchHits.length > 0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
response = esClient.scroll(scrollRequest, RequestOptions.DEFAULT);
scrollId = response.getScrollId();
searchHits = response.getHits().getHits();
for (SearchHit searchHit : searchHits) {
i++;
System.out.println(searchHit.getSourceAsString());
}
if (i > 10) {
break;
}
}*/
}
}
}
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
private static String scheme = "http";
private static String host = "202.107.24.16";
private static int port = 9201;
private static String username = "elas918273";
private static String password = "Elastic#@!123";
private static String auth = "Authorization Type : Basic Auth";
private static String _index = ".security-7";
private static String _type = "_doc";
public static RestHighLevelClient esClient = null;
private static RequestOptions COMMON_OPTIONS = null;
public static RestHighLevelClient ESClientInit() {
//不需要用户名和密码的认证
//esClient = new RestHighLevelClient(RestClient.builder(new HttpHost(hostname, port, scheme)));
//需要用户名和密码的认证
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(host, port, scheme))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
esClient = new RestHighLevelClient(restClientBuilder);
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
builder.setHttpAsyncResponseConsumerFactory(
// 设置查询内容大小限制,默认100 * 1024 * 1024
new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(200 * 1024 * 1024)
);
COMMON_OPTIONS = builder.build();
return esClient;
}
public static void main(String[] args) throws Exception {
//queryAllByHits(ESClientInit());
queryAllByScollData(ESClientInit());
}
/**
* 创建索引
*
* @param esClient
* @throws Exception
*/
public static void indexCreate(RestHighLevelClient esClient) throws Exception {
//创建索引
CreateIndexRequest request = new CreateIndexRequest(".securityxxx-7");
CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);
//拿到响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作: " + acknowledged);
//关闭客户端连接
esClient.close();
}
/**
* 获取索引信息
*
* @param esClient
* @throws Exception
*/
public static void indexQuery(RestHighLevelClient esClient) throws Exception {
//创建索引连接
GetIndexRequest request = new GetIndexRequest(".security-7");
GetIndexResponse getIndexResponse = esClient.indices().get(request, RequestOptions.DEFAULT);
System.out.println("索引查询: " + getIndexResponse.getAliases());
System.out.println("索引查询: " + getIndexResponse.getMappings());
System.out.println("索引查询: " + getIndexResponse.getSettings());
//关闭客户端连接
esClient.close();
}
/**
* @param esClient
* @throws Exception
*/
private static void queryALl(RestHighLevelClient esClient) throws Exception {
//查询索引中的全部数据
SearchRequest request = new SearchRequest();
request.indices(".security-7");
//查询全部 matchAll
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 条件查询
*
* @param esClient
* @throws Exception
*/
private static void queryCondition(RestHighLevelClient esClient) throws Exception {
//查询索引中的全部数据
SearchRequest request = new SearchRequest();
request.indices("user");
//分词中 同时包含李强才可以,因为底层默认使用英文分词器,所以李强会被分为 李,强没办法符合条件所以查询不到
//request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("name","李强")));
//这样是李强字段不可再分,查询name字段中包含此字段的数据
request.source(new SearchSourceBuilder().query(QueryBuilders.matchPhraseQuery("name", "李强")));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 分页查询、部分字段显示、排序
*
* @param esClient
* @throws Exception
*/
private static void queryPage(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices(".security-7");
//构造查询条件 "match_all", "{}"
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//分页
query.from(0); //从第几条数据开始截取 (页码-1)* 每页数量
query.size(2); //每页的数量
String[] excludes = {"name"}; //排除字段
String[] includes = {"tel"}; //展示字段
query.fetchSource(includes, excludes);
//排序
query.sort("create_time", SortOrder.ASC);
request.source(query);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 组合条件查询
*
* @param esClient
* @throws Exception
*/
private static void queryConditionS(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//组合条件查询
//与
// boolQueryBuilder.must(QueryBuilders.matchQuery("name","小"));
// boolQueryBuilder.must(QueryBuilders.matchQuery("sex","性别1"));
// boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex","性别1"));
//或
boolQueryBuilder.should(QueryBuilders.matchQuery("name", "华"));
boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
//排序
builder.sort("tel", SortOrder.ASC);
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 范围查询
*
* @param esClient
* @throws Exception
*/
private static void queryBetween(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
rangeQueryBuilder.gte(30);
rangeQueryBuilder.lte(32);
//排序
builder.sort("tel", SortOrder.ASC);
builder.query(rangeQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 模糊查询(不针对中文)
*
* @param esClient
* @throws Exception
*/
private static void queryLike(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.fuzzyQuery("name", "zhangsan").fuzziness(Fuzziness.ONE));
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 高亮查询
*
* @param esClient
* @throws Exception
*/
private static void queryHighLighter(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhang");
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<h1 color='red'>");
highlightBuilder.postTags("</h1>");
highlightBuilder.field("name");
builder.highlighter(highlightBuilder);
builder.query(termQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 聚合查询(最大值)
*
* @param esClient
* @throws Exception
*/
private static void queryAggregation(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
//分组名称,聚合字段
AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
System.out.println(response);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 聚合查询(group分组)
*
* @param esClient
* @throws Exception
*/
private static void queryGroup(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
System.out.println(response);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
/**
* 查询全部
*/
private static void queryAllByHits(RestHighLevelClient esClient) throws IOException {
Gson gson = new Gson();
// 创建搜索对象
SearchRequest searchRequest = new SearchRequest();
// 查询构建工具
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//排序
//No mapping found for [create_time] in order to sort on
//searchSourceBuilder.sort("create_time", SortOrder.ASC);
// 添加查询条件,通过QueryBuilders获取各种查询
searchSourceBuilder.query(QueryBuilders.matchAllQuery());//"match_all", "{}"
searchRequest.source(searchSourceBuilder);
// 搜索
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
// 解析
SearchHits hits = search.getHits();
SearchHit[] hits1 = hits.getHits();
for (SearchHit hit : hits1) {
// 取出source数据
String itemstring = hit.getSourceAsString();
// 反序列化
HashMap item = gson.fromJson(itemstring, HashMap.class);
System.out.println(item);
}
}
private static void queryAllByScoll1(RestHighLevelClient esClient) throws IOException {
try {
long startTime = System.currentTimeMillis();
/*创建客户端*/
//client startup
//设置集群名称
Settings settings = Settings.builder()
.put("cluster.name", "elsearch")
.put("client.transport.sniff", true)
.build();
//创建client
RestHighLevelClient client = esClient;
List<String> result = new ArrayList<>();
String scrollId = "";
//第一次请求
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//TODO: 设置查询条件
RangeQueryBuilder rangequerybuilder = QueryBuilders
.rangeQuery("inputtime")
.from("2016-12-14 02:00:00").to("2016-12-14 07:59:59");
sourceBuilder.query(QueryBuilders.boolQuery()
.must(QueryBuilders
.matchPhraseQuery("pointid", "W3.UNIT1.10HFC01CT013"))
.must(rangequerybuilder))
.size(100)//如果开启游标,则滚动获取
.sort("inputtime", SortOrder.ASC);
//查询
SearchRequest request = Requests.searchRequest("pointdata");
request.scroll("2m");
request.source(sourceBuilder);
SearchResponse response = client.search(request,null);//.actionGet();
//TODO:处理数据
SearchHits hits = response.getHits();
for (int i = 0; i < hits.getHits().length; i++) {
//System.out.println(hits.getHits()[i].getSourceAsString());
result.add(hits.getHits()[i].getSourceAsString());
}
//记录滚动ID
scrollId = response.getScrollId();
while (true) {
//后续的请求
//scrollId = query.getScollId();
SearchScrollRequestBuilder searchScrollRequestBuilder = null;//client.prepareSearchScroll(scrollId);
// 重新设定滚动时间
//TimeValue timeValue = new TimeValue(30000);
searchScrollRequestBuilder.setScroll("2m");
// 请求
SearchResponse response1 = searchScrollRequestBuilder.get();
//TODO:处理数据
SearchHits hits2 = response1.getHits();
if (hits2.getHits().length == 0) {
break;
}
for (int i = 0; i < hits2.getHits().length; i++) {
result.add(hits2.getHits()[i].getSourceAsString());
}
//下一批处理
scrollId = response1.getScrollId();
}
System.out.println(result.size());
long endTime = System.currentTimeMillis();
System.out.println("Java程序运行时间:" + (endTime - startTime) + "ms");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void queryAllByScoll(RestHighLevelClient esClient) throws IOException {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.should(QueryBuilders.termQuery("match_all","{}"));
// 存活时间,当索引数据量特别大时,出现超时可能性大,此值适当调大
Scroll scroll = new Scroll(TimeValue.timeValueMinutes(10L));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(boolQuery);
searchSourceBuilder.size(5);
SearchRequest searchRequest = new SearchRequest()
// ES7已经去掉type,查询时加type
.indices(_index)
.scroll(scroll)
.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try{
searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
} catch(
IOException e) {
e.printStackTrace();
}
String scrollId = searchResponse.getScrollId();
SearchHit[] searchHits = searchResponse.getHits().getHits();
for(SearchHit searchHit :searchHits){
System.out.println(searchHit.getSourceAsString());
}
//遍历搜索命中的数据,直到没有数据
while(searchHits !=null&&searchHits.length >0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
try {
searchResponse = esClient.scroll(scrollRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
scrollId = searchResponse.getScrollId();
searchHits = searchResponse.getHits().getHits();
if (searchHits != null && searchHits.length > 0) {
for (SearchHit searchHit : searchHits) {
System.out.println(searchHit.getSourceAsString());
}
}
}
//clean scroll
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(scrollId);
ClearScrollResponse clearScrollResponse = null;
try{
clearScrollResponse = esClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
} catch(
IOException e) {
//log.error("clear-scroll-error:{}", e);
}
boolean succeeded = clearScrollResponse.isSucceeded();
System.out.println(succeeded);
}
public static void queryAllByScollData(RestHighLevelClient esClient) throws IOException {
int i = 1,size = 2000,total = 43316300;
for(i=909 ; i<total/size ; i++) {
SearchRequest searchRequest = new SearchRequest();
//Scroll scroll = new Scroll(TimeValue.timeValueMinutes(5L));
//searchRequest.scroll(scroll);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
searchSourceBuilder.query(matchAllQueryBuilder);
searchSourceBuilder.from(i*size);
searchSourceBuilder.size(size);
searchRequest.source(searchSourceBuilder);
SearchResponse response = esClient.search(searchRequest, COMMON_OPTIONS);
//String scrollId = response.getScrollId();
SearchHit[] searchHits = response.getHits().getHits();
//System.out.println(response.getHits().getTotalHits());
for (SearchHit searchHit : searchHits) {
//System.out.println(searchHit.getSourceAsString());
FileUtil.appendString(searchHit.getSourceAsString()+"\n",new File("D:\\aa\\"+i*size+".csv"),"UTF-8");
}
/*while (searchHits != null && searchHits.length > 0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
response = esClient.scroll(scrollRequest, RequestOptions.DEFAULT);
scrollId = response.getScrollId();
searchHits = response.getHits().getHits();
for (SearchHit searchHit : searchHits) {
i++;
System.out.println(searchHit.getSourceAsString());
}
if (i > 10) {
break;
}
}*/
}
}
}
相关推荐
5. **配置文件**:在解压后的目录中,`elasticsearch.yml`是主要的配置文件,用户可以在这里调整内存分配、网络设置、索引策略等参数以适应具体需求。 6. **JVM设置**:Elasticsearch依赖Java虚拟机(JVM),因此...
9. **集群搭建**:要创建多节点集群,只需在不同机器上重复以上步骤,并在`elasticsearch.yml`中设置相同的集群名称和节点间通信端口。 10. **监控与维护**:定期检查节点健康状态、索引分片分布、CPU和内存使用...
《Elasticsearch分词器:elasticsearch-analysis-ik-7.16.2深度解析》 在信息爆炸的时代,搜索引擎的效能成为了数据检索的关键。Elasticsearch作为一款强大的开源搜索引擎,其灵活性和可扩展性备受青睐。而在中文...
`bin`目录下有启动和停止Elasticsearch的脚本,`config`目录包含默认的配置文件如`elasticsearch.yml`。 在运行Elasticsearch之前,我们需要修改`elasticsearch.yml`配置文件。这包括设置节点名称、集群名称、数据...
在现代大数据分析和搜索引擎领域,Elasticsearch(ES)因其高效、灵活的全文检索能力而备受青睐。然而,对于中文这样的多字节语言,如何准确地进行分词是关键。这时,我们就需要引入专门的中文分词器。本文将详细...
Kibana是 Elastic Stack 中的...总之,Kibana 7.16.2是一个强大的数据可视化工具,尤其适用于那些使用Elasticsearch存储和处理数据的组织。通过其丰富的功能和易用性,Kibana使得数据探索和分析变得更为简单和直观。
Elasticsearch(elasticsearch-7.16.2-linux-x86_64.tar.gz适用于Linux x86_64)是一个高度可扩展的开源全文本搜索和分析引擎。它使您可以快速,近乎实时地存储,搜索和分析大量数据。它通常用作支持具有复杂搜索...
包含elasticsearch-7.16.3-linux-x86_64.tar.gz,elasticsearch-head.zip,node-v12.18.1-linux-x64.tar.xz三个安装包,head包已经做了内部修改可以解压直接用
Elasticsearch(elasticsearch-7.16.2-arm64.deb适用于deb aarch64)是一个高度可扩展的开源全文本搜索和分析引擎。它使您可以快速,近乎实时地存储,搜索和分析大量数据。它通常用作支持具有复杂搜索功能和要求的...
7.16.2 版本是 Logstash 的一个重要更新,它提供了一系列的改进和修复,以确保稳定性和性能。 在Logstash 7.16.2 for Linux-x86_64 版本中,我们可以关注以下几个关键知识点: 1. **兼容性与系统需求**:此版本的 ...
Elasticsearch 7.16.3版本可能包含了安全性增强,例如角色基础的访问控制、SSL/TLS加密通信、认证和授权机制,以保护敏感数据。 总的来说,"最新版windows elasticsearch-7.16.3-windows-x86_64.zip"是一个强大的...
最新版linux elasticsearch-7.16.3-linux-x86_64.tar.gz
这个最新的版本,"logstash-7.16.2-linux-x86_64.tar.gz",是专为Linux操作系统设计的64位版本,提供了一套完整的工具集,用于处理和分析来自各种源的日志数据。 1. **Logstash 架构** - 输入(Inputs):Logstash...
5. 兼容性提升:7.16.3 版本可能提高了与其他Elastic产品(如Elasticsearch和Kibana)的兼容性,确保整个 Elastic Stack 的无缝协作。 6. 监控和日志记录:此版本可能提供了更详尽的监控指标和日志记录,帮助管理员...
Linux Kibana 7.16.2 是一个强大的数据可视化和分析工具,它是Elastic Stack(也称为 ELK Stack)的重要组成部分,Elastic Stack包括Elasticsearch、Logstash、Kibana以及Beats。这个最新的版本是为64位Linux系统...
《Linux Kibana 7.16.3:探索数据可视化的新境界》 Kibana是Elastic Stack(以前称为ELK Stack)的关键组件之一,...如果你正使用Elasticsearch,并寻求一个强大而直观的分析界面,那么Kibana 7.16.3绝对值得你尝试。
这个文件夹包含了一系列的可执行文件和配置文件,如`bin`目录下的`elasticsearch.bat`启动脚本,以及`config`目录下的`elasticsearch.yml`配置文件。你需要根据自己的需求修改配置,例如设置集群名称、内存分配、...
3. 数据转发:利用elasticsearch输出插件将处理后的数据发送至Elasticsearch,如`output { elasticsearch { hosts => ["localhost:9200"] index => "my_index" } }`。 五、监控与维护 1. 使用`--configtest`选项...
最新版windows kibana-7.16.3-windows-x86_64.zip
Linux Kibana 7.16.1 是一个强大的数据可视化和分析工具,与Elasticsearch紧密集成,用于处理和展示日志、监控指标和其他结构化数据。它为用户提供了一个直观的界面,以便轻松地搜索、查看和交互式地创建数据仪表板...