elasticsearch: JAVA query case for ES

In recent years, big data technology has emerged across the country, and companies big and small will always involve some big data projects. As a java engineer, adapting to the java development under the big data background database has inevitably become a development path that we must go through. Now what I want to introduce is how to query the elasticsearch database in java.
1. First, we need to establish a connection pool with 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.**.
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)// Indicates the number of
displays.execute().actionGet();
SearchHits hits = response.getHits();
System.out.println("Conditions are available" + 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. Pass parameter
BoolQueryBuilder qb = QueryBuilders.boolQuery();
qb.must(QueryBuilders.termQuery("key", value));
date
qb.must(QueryBuilders.rangeQuery( "datekey").gte(value));
Exact query
qb.must(QueryBuilders.matchQuery(name, value));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326422901&siteId=291194637