第一步:引入maven jar包
com.alibaba
fastjson
1.2.60
org.elasticsearch.client
elasticsearch-rest-high-level-client
7.4.0
org.elasticsearch
elasticsearch
org.elasticsearch.client
elasticsearch-rest-client
org.elasticsearch.client
elasticsearch-rest-client
7.4.0
org.elasticsearch
elasticsearch
7.4.0
测试代码:
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @description:
* @author: z
* @createDate: 2020/3/2 1:19 PM
* @Version: 1.0
*/
public class EsTest {
private static String hosts = "127.0.0.1"; // 集群地址,多个用,隔开
private static int port = 9200; // 使用的端口号
private static String schema = "http"; // 使用的协议
public static List getHostList(){
List hostList = new ArrayList<>();
String[] hostStrs = hosts.split(",");
for (String host : hostStrs) {
hostList.add(new HttpHost(host, port, schema));
}
return hostList;
}
public static RestHighLevelClient getClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(getHostList().toArray(new HttpHost[0])));
return client;
}
public static void main(String[] args) throws InterruptedException, IOException {
try(RestHighLevelClient client = getClient()) {
//判断 是否存在 索引
// boolean exists = client.indices().exists(new GetIndexRequest("student"), RequestOptions.DEFAULT);
// System.out.println(exists);
// GetRequest request = new GetRequest("student","1000");
// GetResponse response = client.get(request, RequestOptions.DEFAULT);
//System.out.println("getById:"+response.getSource());
//Student 属性 id,name,gender 等
//Student user = JSON.parseObject(new String(response.getSourceAsBytes()), Student.class);
//System.out.println(user.getId());
SearchRequest searchRequest = new SearchRequest("student");
// 这个可以理解 (name = '张三' or name = '李四') and gender='man'
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
// .must(QueryBuilders.termQuery("id", "10000")) id =10000
// matchQuery 联想模糊,类似百度搜索框,matchPhraseQuery 类似与sql like 模糊查询
.must(QueryBuilders.boolQuery().should(QueryBuilders.matchPhraseQuery("name", "张三"))
.should(QueryBuilders.matchPhraseQuery("name", "李四")))
.must(QueryBuilders.matchPhraseQuery("gender", "man"))
;
// searchSourceBuilder.fetchSource(new String[]{"id","ts"}, null);//查询字段
// searchSourceBuilder.size(2);//返回记录数
searchRequest.source(new SearchSourceBuilder().query(boolQueryBuilder));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
System.out.println("total:"+hits.getTotalHits());
SearchHit[] searchHits = hits.getHits();
System.out.println("size:"+searchHits.length);
for(SearchHit hit : searchHits) {
System.out.println("json data:"+hit.getSourceAsString());
System.out.println("id:"+hit.getSourceAsMap().get("ts").toString());
// System.out.println("---"+hit.getSourceAsString());
}
//滚动查询
scroll(client);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 获取总记录数
* @param client
* @return
* @throws IOException
*/
public static long getTotal(RestHighLevelClient client) throws IOException {
SearchRequest searchRequest = new SearchRequest("student");
MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(matchAllQueryBuilder);
searchRequest.source(searchSourceBuilder);
CountRequest countRequest = new CountRequest("student");
// System.out.println(countRequest.source().toString());
CountResponse response = client.count(countRequest, RequestOptions.DEFAULT);
System.out.println("total:"+response.getCount());
//打印查询语句字符串
System.out.println(searchSourceBuilder.toString());
return response.getCount();
}
/**
* scroll 滚动查询
* @param client
*/
public static void scroll(RestHighLevelClient client) throws IOException {
//初始化scroll
final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L)); //设定滚动时间间隔
SearchRequest searchRequest = new SearchRequest("student");
searchRequest.scroll(scroll);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//这里查询所有,可以 QueryBuilders.boolQuery() QueryBuilders 设置查询条件,
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.size(2); //设定每次返回多少条数据
searchRequest.source(searchSourceBuilder);
System.out.println(searchSourceBuilder.toString());
SearchResponse searchResponse = null;
searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
String scrollId = searchResponse.getScrollId();
System.out.println(searchResponse.getHits().getTotalHits());
SearchHit[] searchHits = searchResponse.getHits().getHits();
System.out.println("----第一页-----》");
for (SearchHit searchHit : searchHits) {
System.out.println(searchHit.getSourceAsString());
}
//遍历符合搜索条件的数据,直到没有数据
while (searchHits != null && searchHits.length > 0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
scrollId = searchResponse.getScrollId();
searchHits = searchResponse.getHits().getHits();
if (searchHits != null && searchHits.length > 0) {
System.out.println("----下一页-----》");
for (SearchHit searchHit : searchHits) {
System.out.println(searchHit.getSourceAsString());
}
}
}
//清除滚屏
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
//或者用setScrollIds()指定多个scrollId
clearScrollRequest.addScrollId(scrollId);
ClearScrollResponse clearScrollResponse = null;
clearScrollResponse = client.clearScroll(clearScrollRequest,RequestOptions.DEFAULT);
boolean succeeded = clearScrollResponse.isSucceeded();
System.out.println("succeeded:" + succeeded);
}
}
es文章阅读推荐:
https://segmentfault.com/a/1190000016830796