Search - TuPengXiong/TuPengXiong.github.io GitHub Wiki

package tpx.elasticsearch;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;

/**
 * 查询
 * @author tpx
 *
 */
public class Search {

	public static void main(String[] args) {

		Index index = new Index();
		index.createTransportClient();
		Search search = new Search();
		search.printResponse(search.search(index.client));
		index.closeTransportClient();
	}

	public SearchResponse search(TransportClient client) {
		SearchResponse response = client.prepareSearch("tpx")
		        .setTypes("testBulk")
		        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
		        //.setQuery(QueryBuilders.termQuery("user", "testBulk2"))                 // Query
		       // .setPostFilter(QueryBuilders.rangeQuery("_id").from(1).to(18))     // Filter
		        .setFrom(0). //from
		        setSize(60). //数量
		        setExplain(true) 
		        .execute()
		        .actionGet();
		return response;
	}

	public  void printResponse(SearchResponse response) {
		// You will get all individual responses from
		// MultiSearchResponse#getResponses()
			System.out.println(response.toString());
			System.out.println(response.getHits().getHits().length);
	}
}