1、es search sroll 可以遍历索引下所有数据
public class TestDemo { @Test public void searchSroll() { JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig(new HttpClientConfig.Builder("http://192.168.1.100:9200").multiThreaded(true).readTimeout(300000).build()); JestClient client = factory.getObject(); String query = "{" + " "query":{" + " "match_all":{}" + " }" + "}"; try { Search search = new Search.Builder(query).addIndex("my_index").addType("my_type").setParameter(Parameters.SIZE, 5000).setParameter(Parameters.SCROLL, "1m").build(); JestResult result = client.execute(search); String scrollId = result.getJsonObject().get("_scroll_id").getAsString(); System.out.println(scrollId); for (int i = 1; i < 10; i++) { SearchScroll scroll = new SearchScroll.Builder(scrollId, "1m").build(); result = client.execute(scroll); List<Map> list = result.getSourceAsObjectList(Map.class); if (list != null) { System.out.println(list.get(0)); System.out.println(list.size()); } } } catch (Exception e) { e.printStackTrace(); } } }
2、es search sroll 可以遍历索引下所有数据。与上面差别是利用SearchSourceBuilder构造查询条件。
public class TestDemo { //搜索测试 @Test public void JestSearchTest() throws Exception { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("content", "搜索")); Search search = new Search.Builder(searchSourceBuilder.toString()) // multiple index or types can be added. .addIndex("indexdata") .build(); JestClient client = getClient(); SearchResult result = client.execute(search); // List> hits = result.getHits(Klarticle.class); Listarticles = result.getSourceAsObjectList(Klarticle.class); for (Klarticle k : articles) { System.out.println("------->:" + k.getTitle()); } } }