Java之ES查询操作(二)

下面来继续记录并分享ES相关操作

下面来补充两种ES的查询方式,具体实现如下所示:

/**
*	create by wxy_jdhk
*/
public class ElasticSearchUtils {
    //查询方式1
	public void getSearchSourceBuild(TransportClient client) {
		SearchResponse response = client.prepareSearch("index1", "index2")
				.setTypes("type1", "type2")
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				//设置查询条件
				.setQuery(QueryBuilders.termQuery("multi", "test"))
				//设置过滤条件
				.setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))
				.setFrom(0).setSize(60).setExplain(true)
				.get();
		SearchResponse response2 = client.prepareSearch().get();
	}
	
	//查询方式2
	public void getUsingScrollsInJava(TransportClient client) {
		QueryBuilder qb = termQuery("multi", "test");
		SearchResponse scrollResp = client.prepareSearch()
				.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
				.setScroll(new TimeValue(60000))
				.setQuery(qb)
				//每次最多返回100个hits对象
				.setSize(100).get();
		//直到无hits对象返回
		do{
			for(SearchHit hit: scrollResp.getHits().getHits()) {
				//处理hit对象
			}
		} while(scrollResp.getHits().getHits().length != 0);
				
	}
}

你可能感兴趣的:(ElasticSearch)