elasticsearch : JAVA对ES的查询案例

近些年来,大数据的技术已经在全国范围内兴起,不管大小企业总会涉及到一些大数据的项目。作为一名java工程师适应在大数据后台数据库下的java开发必然已成为我们必须要经历的发展道路。而现在我要介绍的就是java实现对elasticsearch 数据库的查询方法,
1、首先我们要建立与es的连接池
private static Client client = null;
public static Client init() {
if (client == null
|| ((TransportClient) client).connectedNodes().isEmpty()) {
synchronized (ESUtil.class) {
try {

Settings settings = Settings.settingsBuilder().put("cluster.name","es-aisinohtxx").put("client.transport.ping_timeout", "20s").build();
client = TransportClient
.builder().settings(settings)
.build()
.addTransportAddress(
new InetSocketTransportAddress(InetAddress
.getByName("192.168.**.***"), 9300));
System.out.println("连接成功!");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return client;
}

2、创建公共查询接口
public static JSONArray searchUtil(BoolQueryBuilder qb, int from,int pagesize,String indexname,String typename){
Client client = ClientInit.init();
SortOrder sortOrder = SortOrder.DESC;
SearchResponse response = client.prepareSearch(indexname)
.setTypes(typename)
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(qb) // Query查询方法
.setFrom(from).setSize(pagesize)
.addSort("id", sortOrder)
.setExplain(true)// 表示显示数量
.execute().actionGet();
SearchHits hits = response.getHits();
System.out.println("符合条件的有" + hits.getTotalHits());
count = (int) hits.getTotalHits();
SearchHit[] searchHists = hits.getHits();
JSONArray jsonArray = new JSONArray();
for (SearchHit sh : searchHists) {
JSONObject jsonobj = JSONObject.fromObject(sh.getSource());
jsonArray.add(jsonobj);
}
return jsonArray;
}
3、传参
BoolQueryBuilder qb = QueryBuilders.boolQuery();
qb.must(QueryBuilders.termQuery("key", value));
日期
qb.must(QueryBuilders.rangeQuery("datekey").gte(value));
精确查询
qb.must(QueryBuilders.matchQuery(name, value));

你可能感兴趣的:(elasticsearch : JAVA对ES的查询案例)